python 的字元串常用函數
-
- 1. str.capitalize()
- 2. str.center(width, fillchar)
- 3. str.count(sub, start= 0,end=len(str))
- 4. bytes.decode(encoding="utf-8", errors="strict")
- 5. str.encode(encoding='UTF-8',errors='strict')
- 6. str.endswith(suffix[, start[, end]])
- 7. str.expandtabs(tabsize=8)
- 8. str.find(str, beg=0, end=len(string))
- 9. str.index(str, beg=0, end=len(string))
- 10. str.isalnum()
- 11. str.isalpha()
- 12. str.isdigit()
- 13. str.islower()
- 14. str.isnumeric()
- 15. str.isspace()
- 16. str.istitle()
- 17. str.isupper()
- 18. str.join(sequence)
- 19. len( s )
- 20. str.ljust(width[, fillchar])
- 21. str.lower()
- 22. str.lstrip([chars])
- 23. str.maketrans(intab, outtab)
- 24. max(str)
- 25. min(str)
- 26. str.replace(old, new[, max])
- 27. str.rfind(str, beg=0 end=len(string))
- 28. str.rindex(str, beg=0 end=len(string))
- 29. str.rjust(width[, fillchar])
- 30. str.rstrip([chars])
- 31. str.split(str="", num=string.count(str))
- 32. str.splitlines([keepends])
- 33. str.startswith(substr,beg=0,end=len(string))
- 34. str.strip([chars])
- 35. str.swapcase()
- 36. str.title()
- 37. str.translate(table)、bytes.translate(table[, delete])、bytearray.translate(table[, delete])
- 38. str.upper()
- 39. str.zfill(width)
- 40. str.isdecimal()
- s.isdigit、isdecimal 和 s.isnumeric 差別
1. str.capitalize()
-
用途
将字元串的第一個字元轉換為大寫。
- 執行個體
str = 'hello world' print(str.capitalize()) out: Hello world
2. str.center(width, fillchar)
-
用途
傳回一個指定的寬度 width 居中的字元串,fillchar 為填充的字元,預設為空格。
- 執行個體
str = 'hello world' print(str.center(20, '*')) out: ****hello world*****
3. str.count(sub, start= 0,end=len(str))
-
用途
傳回 sub 在 str 裡面出現的次數,如果 beg 或者 end 指定則傳回指定範圍内(左閉右開) sub 出現的次數。
- 執行個體
str = 'hello world' print(str.count('o', 4, 8)) out: 2
4. bytes.decode(encoding=“utf-8”, errors=“strict”)
-
用途
decode() 方法以指定的編碼格式解碼 bytes 對象。預設編碼為 ‘utf-8’。
Python3 中沒有 decode 方法,但我們可以使用 bytes 對象的 decode() 方法來解碼給定的 bytes 對象,這個 bytes 對象可以由 str.encode() 來編碼傳回。
- 參數
- encoding:要使用的編碼,如"UTF-8"。
- errors:設定不同錯誤的處理方案。預設為 ‘strict’,意為編碼錯誤引起一個UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通過 codecs.register_error() 注冊的任何值。
- 執行個體
str = "解碼執行個體" str_utf8 = str.encode("UTF-8") str_gbk = str.encode("GBK") print(str) # print("UTF-8 編碼:", str_utf8) print("GBK 編碼:", str_gbk) print("UTF-8 解碼:", str_utf8.decode('UTF-8','strict')) print("GBK 解碼:", str_gbk.decode('GBK','strict')) out: 解碼執行個體 UTF-8 編碼: b'\xe8\xa7\xa3\xe7\xa0\x81\xe5\xae\x9e\xe4\xbe\x8b' GBK 編碼: b'\xbd\xe2\xc2\xeb\xca\xb5\xc0\xfd' UTF-8 解碼: 解碼執行個體 GBK 解碼: 解碼執行個體
5. str.encode(encoding=‘UTF-8’,errors=‘strict’)
-
用途
以指定的編碼格式編碼字元串。errors參數可以指定不同的錯誤處理方案。
如果出錯預設報一個ValueError 的異常,除非 errors 指定的是’ignore’或者’replace’。
該方法傳回編碼後的字元串,它是一個 bytes 對象。
- 參數
- encoding:要使用的編碼,如"UTF-8"。
- errors:設定不同錯誤的處理方案。預設為 ‘strict’,意為編碼錯誤引起一個UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通過 codecs.register_error() 注冊的任何值。
- 執行個體
str = "編碼執行個體" str_utf8 = str.encode("UTF-8") str_gbk = str.encode("GBK") print(str) print("UTF-8 編碼:", str_utf8) print("GBK 編碼:", str_gbk) out: 編碼執行個體 UTF-8 編碼: b'\xe7\xbc\x96\xe7\xa0\x81\xe5\xae\x9e\xe4\xbe\x8b' GBK 編碼: b'\xb1\xe0\xc2\xeb\xca\xb5\xc0\xfd'
6. str.endswith(suffix[, start[, end]])
-
用途
endswith() 方法用于判斷字元串是否以指定字尾結尾,如果以指定字尾結尾傳回 True,否則傳回 False。
- 參數
- suffix:該參數可以是一個字元串或者是一個元素。
- start:字元串中的開始位置,開區間。
- end:字元中結束位置,閉區間。
- 執行個體
str = 'Hello World' print(str.endswith('d', 0, 10)) print(str.endswith('d', 0, 11)) out: False True
7. str.expandtabs(tabsize=8)
-
用途
expandtabs() 方法把字元串中的 tab 符号 \t 轉為空格,tab 符号 \t 預設的空格數是 8,在第 0、8、16…等處給出制表符位置,如果目前位置到開始位置或上一個制表符位置的字元數不足 8 的倍數則以空格代替。
該方法傳回字元串中的 tab 符号 \t 轉為空格後生成的新字元串。
- 參數
- tabsize:指定轉換字元串中的 tab 符号 \t 轉為空格的字元數。
- 執行個體
str = "runoob\t12345\tabc" print('原始字元串:', str) # 預設 8 個空格 # runnob 有 6 個字元,後面的 \t 填充 2 個空格 # 12345 有 5 個字元,後面的 \t 填充 3 個空格 print('替換 \\t 符号:', str.expandtabs()) # 2 個空格 # runnob 有 6 個字元,剛好是 2 的 3 倍,後面的 \t 填充 2 個空格 # 12345 有 5 個字元,不是 2 的倍數,後面的 \t 填充 1 個空格 print('使用 2 個空格替換 \\t 符号:', str.expandtabs(2)) # 3 個空格 print('使用 3 個空格:', str.expandtabs(3)) # 4 個空格 print('使用 4 個空格:', str.expandtabs(4)) # 5 個空格 print('使用 5 個空格:', str.expandtabs(5)) # 6 個空格 print('使用 6 個空格:', str.expandtabs(6)) out: 原始字元串: runoob 12345 abc 替換 \t 符号: runoob 12345 abc 使用 2 個空格替換 \t 符号: runoob 12345 abc 使用 3 個空格: runoob 12345 abc 使用 4 個空格: runoob 12345 abc 使用 5 個空格: runoob 12345 abc 使用 6 個空格: runoob 12345 abc
8. str.find(str, beg=0, end=len(string))
-
用途
檢測字元串中是否包含子字元串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍内,如果指定範圍内如果包含指定索引值,傳回的是索引值在字元串中的起始位置。如果不包含索引值,傳回 -1。
- 參數
- str:指定檢索的字元串
- beg:開始索引,預設為0,閉區間。
- end:結束索引,開區間,預設為字元串的長度。
- 執行個體
str = 'Hello World' print(str.find('H', 0, 4)) print(str.find('0', 0, 5)) out: 0 -1
9. str.index(str, beg=0, end=len(string))
-
用途
檢測字元串中是否包含子字元串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍内,該方法與 python find()方法一樣,隻不過如果str不在 string中會報一個異常。
如果包含子字元串傳回開始的索引值,否則抛出異常。
- 參數
- str:指定檢索的字元串
- beg:開始索引,預設為0,閉區間。
- end:結束索引,開區間,預設為字元串的長度。
- 執行個體
str = 'Hello World' print(str.index('H', 0, 4)) print(str.index('0', 0, 5)) out: 0 ValueError: substring not found
10. str.isalnum()
-
用途
檢測字元串是否由字母和數字組成。
如果字元串至少有一個字元并且所有字元隻包含字母或數字則返 回 True,否則傳回 False。
- 執行個體
print('123'.isalnum()) print('abc'.isalnum()) print('123abc'.isalnum()) print(''.isalnum()) print('123abc_'.isalnum()) print('123abc '.isalnum()) out: True True True False False False
11. str.isalpha()
-
用途
檢測字元串是否隻由字母或文字組成。
如果字元串至少有一個字元并且所有字元隻包含字母或中文字則傳回 True, 否則傳回 False。
- 執行個體
print('abc'.isalpha()) print('文字'.isalpha()) print('abc文字'.isalpha()) print(''.isalpha()) print('abc123'.isalpha()) out: True True True False False
12. str.isdigit()
-
用途
檢測字元串是否隻由數字組成。
如果字元串隻包含數字則傳回 True 否則傳回 False。
- 執行個體
print('123'.isdigit()) print('123abc'.isdigit()) print(''.isdigit()) out: True False False
13. str.islower()
-
用途
檢測字元串是否由小寫字母組成。
如果字元串中包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是小寫,則傳回 True,否則傳回 False。
- 執行個體
print('abc'.islower()) print('abc_!123'.islower()) print('Abc'.islower()) print(''.islower()) out: True True False False
14. str.isnumeric()
-
用途
檢測字元串是否隻由數字組成,數字可以是: Unicode 數字,全角數字(雙位元組),羅馬數字,漢字數字。
指數類似 ² 與分數類似 ½ 也屬于數字。
如果字元串中隻包含數字字元,則傳回 True,否則傳回 False。
- 執行個體
str = "runoob2016" print (str.isnumeric()) str = "23443434" print (str.isnumeric()) s = '\u00B23455' # s = '²3455' print(s.isnumeric()) s = '\u00BD' # s = '½' print(s.isnumeric()) a = "\u0030" # unicode for 0 print(a.isnumeric()) b = "\u00B2" # unicode for ² print(b.isnumeric()) c = "10km2" print(c.isnumeric()) out: False True True True True True False
15. str.isspace()
-
用途
檢測字元串是否隻由空白字元組成(空白符包含:空格、制表符(\t)、換行(\n)、回車(\r)等,空字元串不算空白符)。
如果字元串中隻包含空格,則傳回 True,否則傳回 False。
- 執行個體
print (' \t\r\n'.isspace()) print(' 12 '.isspace()) out: True False
16. str.istitle()
-
用途
檢測字元串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫。
如果字元串中所有的單詞拼寫首字母為大寫,且其他字母為小寫則傳回 True,否則傳回 False。
- 執行個體
print ('Hello World'.istitle()) print('hello World'.istitle()) print('HelloWorld'.istitle()) out: True False False
17. str.isupper()
-
用途
檢測字元串中所有的字母是否都為大寫。
如果字元串中包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是大寫,則傳回 True,否則傳回 False。
- 執行個體
print('ABC'.isupper()) print('ABC_!123'.isupper()) print('Abc'.isupper()) print(''.isupper()) out: True True False False
18. str.join(sequence)
-
用途
用于将序列中的元素以指定的字元連接配接生成一個新的字元串。
- 參數
- sequence:要連接配接的元素序列。
- 執行個體
str = ['a', 'b', 'c', 'd'] print("-".join(str)) out: a-b-c-d
19. len( s )
-
用途
傳回對象(字元、清單、元組等)長度或項目個數。
- 參數
- s:對象。
- 執行個體
str = 'hello world' print(len(str)) arr = ['a', 'b', 'c', 'd'] print(len(arr)) out: 11 4
20. str.ljust(width[, fillchar])
-
用途
傳回一個原字元串左對齊,并使用空格填充至指定長度的新字元串。如果指定的長度小于原字元串的長度則傳回原字元串。
- 參數
- width:指定字元串長度。
- fillchar:填充字元,預設為空格。
- 執行個體
str = ' hello world' print(str.ljust(20, '*')) out: hello world******
21. str.lower()
-
用途
轉換字元串中所有大寫字元為小寫。
- 執行個體
str = 'Hello World 123' print(str.lower()) out: hello world 123
22. str.lstrip([chars])
-
用途
用于截掉字元串左邊的空格或指定字元。
- 參數
- char:指定截取的字元。
- 執行個體
str = ' hello world ' print(str.lstrip()) str = 'xxhello worldxx' print(str.lstrip('x')) out: hello world hello worldxx
23. str.maketrans(intab, outtab)
-
用途
用于建立字元映射的轉換表,對于接受兩個參數的最簡單的調用方式,第一個參數是字元串,表示需要轉換的字元,第二個參數也是字元串表示轉換的目标。
兩個字元串的長度必須相同,為一一對應的關系。
注:Python3.4 已經沒有 string.maketrans() 了,取而代之的是内建函數: bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。
- 參數
- intab:字元串中要替代的字元組成的字元串。
- outtab:相應的映射字元的字元串。
- 執行個體
intab = "aeo" outtab = "123" trantab = str.maketrans(intab, outtab) str = "hello world" print (str.translate(trantab)) out: h2ll3 w3rld
24. max(str)
-
用途
傳回字元串中最大的字母。
在有大小寫的字元串中傳回的是小寫字母的最大值。
- 參數
- str:字元串。
- 執行個體
str = 'aAbBcCdD' print(max(str)) out: d
25. min(str)
-
用途
傳回字元串中最小的字母。
- 參數
- istr:字元串。
- 執行個體
str = 'aAbBcCdD' print(min(str)) out: a
26. str.replace(old, new[, max])
-
用途
把字元串中的 old(舊字元串) 替換成 new(新字元串),如果指定第三個參數max,則替換不超過 max 次。
- 參數
- old:将被替換的子字元串。
- new:新字元串,用于替換old子字元串。
- max:可選字元串, 替換不超過 max 次。
- 執行個體
str = 'hello world' print(str.replace('o', 'x')) out: hellx wxrld
27. str.rfind(str, beg=0 end=len(string))
-
用途
傳回字元串最後一次出現的位置,如果沒有比對項則傳回-1。
- 參數
- str:查找的字元串。
- beg:開始查找的位置,預設為0,閉區間。
- end:結束查找位置,開區間,預設為字元串的長度。
- 執行個體
str = 'hello world' print(str.replace('o', 'x')) print(str.rfind('o')) print(str.rfind('o', 0, 4)) out: 7 -1
28. str.rindex(str, beg=0 end=len(string))
-
用途
傳回子字元串 str 在字元串中最後出現的位置,如果沒有比對的字元串會報異常。
- 參數
- str:查找的字元串。
- beg:開始查找的位置,預設為0,閉區間。
- end:結束查找位置,開區間,預設為字元串的長度。
- 執行個體
str = 'hello world' print(str.replace('o', 'x')) print(str.rfind('o')) print(str.rfind('o', 0, 4)) out: 7 ValueError: substring not found
29. str.rjust(width[, fillchar])
-
用途
傳回一個原字元串右對齊,并使用空格填充至長度 width 的新字元串。如果指定的長度小于字元串的長度則傳回原字元串。
- 參數
- width:指定字元串長度。
- fillchar:填充字元,預設為空格。
- 執行個體
str = ' hello world' print(str.rjust(20, '*')) out: ******* hello world
30. str.rstrip([chars])
-
用途
删除 string 字元串末尾的指定字元(預設為空格)。
- 參數
- char:指定截取的字元。
- 執行個體
str = ' hello world ' print(str.rstrip()) str = 'xxhello worldxx' print(str.rstrip('x')) out: hello world xxhello world
31. str.split(str="", num=string.count(str))
-
用途
通過指定分隔符對字元串進行切片,如果第二個參數 num 有指定值,則分割為 num+1 個子字元串。
傳回分割後的字元串清單。
- 參數
- str:分隔符,預設為所有的空字元,包括空格、換行(\n)、制表符(\t)等。
- num:分割次數。預設為 -1, 即分隔所有。
- 執行個體
print('he\tllo wor\nld'.split()) print('hello world'.split('o')) print('hello world'.split('o', 1)) out: ['he', 'llo', 'wor', 'ld'] ['hell', ' w', 'rld'] ['hell', ' world']
32. str.splitlines([keepends])
-
用途
按照行(’\r’, ‘\r\n’, \n’)分隔,傳回一個包含各行作為元素的清單。
- 參數
- keepends:在輸出結果裡是否去掉換行符(’\r’, ‘\r\n’, \n’),預設為 False,不包含換行符,如果為 True,則保留換行符。
- 執行個體
print('ab c\n\nde fg\rkl\r\n'.splitlines()) print('ab c\n\nde fg\rkl\r\n'.splitlines(True)) out: ['ab c', '', 'de fg', 'kl'] ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
33. str.startswith(substr,beg=0,end=len(string))
-
用途
用于檢查字元串是否是以指定子字元串開頭,如果是則傳回 True,否則傳回 False。如果參數 beg 和 end 指定值,則在指定範圍内檢查。
- 參數
- substr:指定的子字元串。
- beg:可選參數用于設定字元串檢測的起始位置,閉區間。
- end:可選參數用于設定字元串檢測的結束位置,開區間。
- 執行個體
print('hello world'.startswith('h')) print('hello world'.startswith('e', 1)) out: True True
34. str.strip([chars])
-
用途
用于移除字元串頭尾指定的字元(預設為空格)或字元序列。
注意:該方法隻能删除開頭或是結尾的字元,不能删除中間部分的字元。
- 參數
- chars:移除字元串頭尾指定的字元序列,如果不帶參數,預設是清除兩邊的空白符,例如:/n, /r, /t, ’ '。
- 執行個體
# strip() 處理的時候,如果不帶參數,預設是清除兩邊的空白符,例如:/n, /r, /t, ' ')。 print(' hello world\n'.strip()) # 隻要頭尾包含有指定字元序列中的字元就删除,并不需要順序一緻 print('123abc321'.strip('12')) out: hello world 3abc3
35. str.swapcase()
-
用途
用于對字元串的大小寫字母進行轉換。
傳回大小寫字母轉換後生成的新字元串。
- 執行個體
print('Hello World'.swapcase()) out: hELLO wORLD
36. str.title()
-
用途
根據參數table給出的表(包含 256 個字元)轉換字元串的字元,要過濾掉的字元放到 deletechars 參數中。
注意,非字母後的第一個字母将轉換為大寫字母
- 執行個體
# 所有單詞的首字母都轉化為大寫 print('hello world'.title()) # 非字母後的第一個字母将轉換為大寫字母 print('acb 1d_e f'.title()) out: Hello World Acb 1D_E F
37. str.translate(table)、bytes.translate(table[, delete])、bytearray.translate(table[, delete])
-
用途
傳回"标題化"的字元串,就是說所有單詞的首個字母轉化為大寫,其餘字母均為小寫(見 istitle())。
注意,str 類型的 translate() 函數隻接受一個參數
- 參數
- table:翻譯表,翻譯表是通過 maketrans() 方法轉換而來。
- deletechars:字元串中要過濾的字元清單。
- 執行個體
table = {'e': '0', 'o': '1', 'd': '2'} # 映射表中必須全部是字元串 trantab = str.maketrans(table) # 制作翻譯表 str = 'hello world' print(str.translate(trantab)) out: h0ll1 w1rl2
38. str.upper()
-
用途
将字元串中的小寫字母轉為大寫字母。
- 執行個體
print('abc123'.upper()) out: ABC123
39. str.zfill(width)
-
用途
傳回指定長度的字元串,原字元串右對齊,前面填充0。
- 參數
- width:指定字元串的長度。原字元串右對齊,前面填充0。
- 執行個體
print('hello world'.zfill(10)) # 指定長度小于原字元串長度,傳回原字元串 print('hello world'.zfill(20)) out: hello world 000000000hello world
40. str.isdecimal()
-
用途
檢查字元串是否隻包含十進制字元。這種方法隻存在于unicode對象。
如果字元串是否隻包含十進制字元傳回True,否則傳回False。
注意: python2 中定義一個十進制字元串,隻需要在字元串前添加 ‘u’ 字首即可。
- 執行個體
print('123'.isdecimal()) print('3.14'.isdecimal()) # 小數不行 print('abc123'.isdecimal()) out: True False False
s.isdigit、isdecimal 和 s.isnumeric 差別
-
isdigit()
True: Unicode數字,byte數字(單位元組),全角數字(雙位元組)
False: 漢字數字,羅馬數字,小數
Error: 無
-
isdecimal()
True: Unicode數字,全角數字(雙位元組)
False: 羅馬數字,漢字數字,小數
Error: byte數字(單位元組)
-
isnumeric()
True: Unicode 數字,全角數字(雙位元組),漢字數字
False: 小數,羅馬數字
Error: byte數字(單位元組)
- 執行個體
num = "1" #unicode num.isdigit() # True num.isdecimal() # True num.isnumeric() # True num = "1" # 全角 num.isdigit() # True num.isdecimal() # True num.isnumeric() # True num = b"1" # byte num.isdigit() # True num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal' num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric' num = "IV" # 羅馬數字 num.isdigit() # False num.isdecimal() # False num.isnumeric() # False num = "四" # 漢字 num.isdigit() # False num.isdecimal() # False num.isnumeric() # True num = "3.14" # 小數 num.isdigit() # False num.isdecimal() # False num.isnumeric() # False