Python 字元串(str)
字元串是 Python 中最常用的資料類型。我們可以使用引号('或")來建立字元串。建立字元串很簡單,隻要為變量配置設定一個值即可。
var1 = "Hello World!"
var2 = 'DaoKe ChuZi'
字元串的操作
1.檢視字元串有那些方法
>>> a = "abc"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
2.通過[]截取字元串的方式取值
>>> a = "Hello Word!"
>>> a[:8]
'Hello Wo'
>>> a[:-2]
'Hello Wor'
3.字元串的更新,就如同對一個字元串重新指派
>>> a
'Hello Word!'
>>> a = "HAHAHA"
>>> a
'HAHAHA'
轉義字元
在需要在字元中使用特殊字元時,python用反斜杠()轉義字元
轉義字元 | 描述 |
---|---|
\(在行尾時) | 續行符 |
\\ | 反斜杠符号 |
\' | 顯示單引号 |
" | 顯示雙引号 |
\n | 換行 |
\r | 回車 |
Python字元串運算符
下表執行個體變量a值為字元串 "Hello",b變量值為 "Python":
操作符 | 描述 | 執行個體 |
---|---|---|
+ | 字元串連接配接 | a + b 輸出結果: HelloPython |
* | 重複輸出字元串 | a*2 輸出結果: HelloHello |
[] | 通過索引擷取字元串中字元 | a[1] 輸出結果 e |
[ : ] | 截取字元串中的一部分 | a[1:4] 輸出結果 ell |
in | 成員運算符 - 如果字元串中包含給定的字元傳回 True | "H" in a True |
not in | 成員運算符 - 如果字元串中不包含給定的字元傳回 True | "W" not in a True |
Python字元串格式化
Python 支援格式化字元串的輸出 。盡管這樣可能會用到非常複雜的表達式,但最基本的用法是将一個值插入到一個有字元串格式符 %s 的字元串中。
>>> print ("我叫 %s 今年 %d 歲!" % ('小明', 10))
我叫 小明 今年 10 歲!
符号 | 描述 |
---|---|
%s | 格式化字元串 |
%d | 格式化整數 |
%f | 格式化浮點數字,可指定小數點後的精度 |
Python字元串内置函數:
1.将字元串的第一個字元轉換為大寫capitalize():
>>> a = "hello word!"
>>> a.capitalize()
'Hello word!'
2.傳回一個指定的寬度 width 居中的字元串,fillchar 為填充的字元,預設為空格center()
>>> a = "www.umout.com"
>>> a
'www.umout.com'
>>> a.center(40,"*")
'*************www.umout.com**************'
3.用于統計字元串裡某個字元出現的次數count(str, beg= 0,end=len(string))
統計"o" 在字元串a 中出現的次數
>>> a
'www.umout.com'
>>> a.count("o")
2
4.判斷字元串是否依指定字尾結尾,是傳回True否則傳回False:endswith()
>>> a
'www.umout.com'
>>> a.endswith("m")
True
>>> a.endswith("o")
False
5.預設把字元串中的 tab 符号('\t')轉為空格,tab 符号('\t')預設的空格數是8,expandtabs()
[[email protected]#>> /tmp]#cat a.py
# !/bin/bash/env python3
# _*_coding:utf-8_*_
str = "this is\tstring example....wow!!!"
print("原始字元串: " + str)
print ("替換 \\t 符号: " + str.expandtabs())
print ("使用16個空格替換 \\t 符号: " + str.expandtabs(16))
輸出内容:
原始字元串8個空格: this is string example....wow!!!
替換 \t 符号為空格: this is string example....wow!!!
使用16個空格替換 \t 符号: this is string example....wow!!!
6.檢測字元串中是否包含子指定的字元串,(可以指定檢測的起始點)如果包含子傳回開始的索引值,否則傳回-1;預設從左往右,rfind()從右往左;find()
>>> a
'www.umout.com'
>>> a.find("umout")
4
>>> a.find("umout",3,10)
4
>>> a.find("xxx")
-1
>>> a.rfind("o")
11
>>> a.rfind("o",-7,-2)
6
7.檢測字元串是否由字母和數字組成,是傳回True否則傳回False isalnum()
>>> hostname = "LinuxName"
>>> hostname.isalnum()
True
>>> hostname2 = "LinuxName123--"
>>> hostname2.isalnum()
False
8.檢測字元串是否隻有字母組成,是傳回True否則傳回False isalpha()
>>> name = "Jack"
>>> name.isalpha()
True
>>> name2 = "Jack li"
>>> name2.isalpha()
False
9.檢測字元串是否隻有(阿拉伯)數字組成,是傳回True否則傳回False isdigit()
>>> age = "12"
>>> age.isdigit()
True
>>> age2 = "12y"
>>> age2.isdigit()
False
10.檢測字元串是否隻有小寫組成(區分大小寫的)字元都算是小寫,是傳回True否則傳回False islower()
>>> name = "bao lin8888--==$$%%##¥¥"
>>> name.islower()
True
>>> name2 = "bao linAA"
>>> name2.islower()
False
11.檢測字元串是否隻由(Unicode)數字組成,是傳回True否則傳回False isnumeric()
>>> age = "四44肆④"
>>> age.isnumeric()
True
>>> age = "33oneIX"
>>> age.isnumeric()
False
12.檢測字元串是否隻由空格組成(或\t \n \r),是傳回True否則傳回False isspace()
>>> name = " \t \n \r "
>>> name.isspace()
True
>>> name = " \t xxx \n "
>>> name.isspace()
False
13.檢測字元串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫;是傳回True否則傳回False istitle()
>>> name = "My Name Is Daoke Chuzi"
>>> name.istitle()
True
>>> name = "My name is daoKe chuzi"
>>> name.istitle()
False
14.檢測字元串中所有的字母是否都為大寫;是傳回True否則傳回False isupper()
>>> name = "MY NAME IS DAOKE CHUZI"
>>> name.isupper()
True
>>> names = "JAck Main"
>>> names.isupper()
False
15.指定的字元連接配接生成一個新的字元串;join()
>>> name = ("my","name","is","chuzi")
>>> "-".join(name)
'my-name-is-chuzi'
>>> names = "my name is daoke"
>>> "-".join(names)
'm-y- -n-a-m-e- -i-s- -d-a-o-k-e'
16.傳回字元串長度;len()
>>> name = "Jack li"
>>> len(name)
7
17.傳回一個原字元串左(右)對齊,預設使用空格填充至指定長度的新字元串。如果指定的長度小于原字元串的長度則傳回原字元串;ljust() rjust()
>>> name
'MY NAME IS DAOKE CHUZI'
>>> name.ljust(50)
'MY NAME IS DAOKE CHUZI '
>>> name.ljust(10)
'MY NAME IS DAOKE CHUZI'
>>> name.ljust(40)
'MY NAME IS DAOKE CHUZI '
>>> name.ljust(40,"*")
'MY NAME IS DAOKE CHUZI******************'
18.轉換字元串中所有大寫字元為小寫;lower()
>>> name
'My NAME IS chuzi!!!'
>>> name.lower()
'my name is chuzi!!!'
>>> name.lower()
19.截掉字元串左(右、兩邊)邊的空格或指定字元;兩邊strip()、左邊lstrip()、右邊rstrip()
>>> str
' this is string example....wow!!! '
>>> str.strip()
'this is string example....wow!!!'
>>> str.lstrip()
'this is string example....wow!!! '
>>> str.rstrip()
' this is string example....wow!!!'
20.把字元串中的 old(舊字元串) 替換成 new(新字元串),如果指定第三個參數max,則替換不超過 max 次;replace()
>>> names
'abc is abc bcd is abc this abc'
>>> names.replace("abc","ABC")
'ABC is ABC bcd is ABC this ABC'
>>> names.replace("abc","ABC",3)
'ABC is ABC bcd is ABC this abc'
21.指定分隔符對字元串進行切片,如果參數num 有指定值,就會依照指定num個子分隔字元串;split()
>>> str
'this is string example....wow!!!'
>>> str.split()
['this', 'is', 'string', 'example....wow!!!']
>>> str.split("i",1)
['th', 's is string example....wow!!!']
>>> str.split("i",2)
['th', 's ', 's string example....wow!!!']
22.按照行分隔,傳回一個包含各行作為元素的清單,将\n的參數值去除;splitlines()
[[email protected]#>> ~]#cat a.py
# !/bin/bash/env python3
# _*_coding:utf-8_*_
str = 'this is \nstring example....\nwow!!!'
print(str.splitlines())
print(str)
[[email protected]#>> ~]#python3 a.py
['this is ', 'string example....', 'wow!!!']
this is
string example....
wow!!!
23.檢查字元串是否是以指定子字元串開頭,如果是則傳回 True,否則傳回 False;可以指定下标的位置;startswith()
>>> str = "this is string example....wow!!!"
>>> str.startswith("this")
True
>>> str.startswith("this",2,8)
False
>>> str.startswith("is",5,8)
True
24.用于對字元串的大小寫字母進行轉換;swapcase()
>>> str = "this IS string example....WOW!!!"
>>> str.swapcase()
'THIS is STRING EXAMPLE....wow!!!'
25.所有單詞都是以大寫開始,其餘字母均為小寫;title()
>>> str = "this IS string example....WOW!!!"
>>> str.title()
'This Is String Example....Wow!!!'
26.将字元串中的小寫字母轉為大寫字母;upper()
>>> str = "this IS string example....WOW!!!"
>>> str.upper()
'THIS IS STRING EXAMPLE....WOW!!!'
27.檢查字元串是否隻包含十進制字元;isdecimal()
>>> age = "2016"
>>> age.isdecimal()
True
>>> age = "2016 "
>>> age.isdecimal()
False
#使用strip去除空格後,繼續使用isdecimal判斷
>>> age.strip().isdecimal()
True
28.判斷一個值,是不是指定的類型;isinstance(o,t)
name = "zhangsan"
age = 18
aihao = ["nv","eat"]
print(isinstance(name, str)) # 判斷name是不是 字元串
print(isinstance(age, str)) # 判斷age 是不是 字元串
print(isinstance(age, int))
print(isinstance(aihao,list)) # 判斷aihao 是不是清單
輸出:
True
False
True
True
轉載于:https://www.cnblogs.com/baolin2200/p/6290208.html