幾個Python的字符串常用內建函數
1.方法:Python3 isdigit()方法
描述:Python isdigit() 方法檢測字符串是否只由數字組成。
語法:str.isdigit()
參數:無
返回值:如果字符串只包含數字則返回 True 否則返回 False。
實例:
1 str = "123456"; 2 print (str.isdigit()) 3 4 str = "abcdef" 5 print (str.isdigit()) 6 7 8 # 輸出結果 9 True 10 False
2.方法:Python3 replace()方法
描述:replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次。
語法:str.replace(old, new[, max])
參數:
- old -- 將被替換的子字符串。
- new -- 新字符串,用於替換old子字符串。
- max -- 可選字符串, 替換不超過 max 次
返回值:返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
實例:
1 str = "www.w3cschool.cc" 2 print ("菜鳥教程舊地址:", str) 3 print ("菜鳥教程新地址:", str.replace("w3cschool.cc", "runoob.com")) 4 5 str = "this is string example....wow!!!" 6 print (str.replace("is", "was", 3)) 7 8 9 # 輸出結果 10 菜鳥教程舊地址: www.w3cschool.cc 11 菜鳥教程新地址: www.runoob.com 12 thwas was string example....wow!!!
3.方法:Python3 find()方法
描述:find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,如果指定范圍內如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。
語法:str.find(str, beg=0, end=len(string))
參數:
- str -- 指定檢索的字符串
- beg -- 開始索引,默認為0。
- end -- 結束索引,默認為字符串的長度。
返回值:如果包含子字符串返回開始的索引值,否則返回-1。
實例:
1 str1 = "Runoob example....wow!!!" 2 str2 = "exam"; 3 4 print (str1.find(str2)) 5 print (str1.find(str2, 5)) 6 print (str1.find(str2, 10)) 7 8 # 輸出結果 9 7 10 7 11 -1
擴展實例(Python 3.0+):
1 # 實例(Python 3.0+) 2 3 >>>info = 'abca' 4 >>> print(info.find('a')) # 從下標0開始,查找在字符串里第一個出現的子串,返回結果:0 5 0 6 >>> print(info.find('a', 1)) # 從下標1開始,查找在字符串里第一個出現的子串:返回結果3 7 3 8 >>> print(info.find('3')) # 查找不到返回-1 9 -1 10 >>>
4.方法:Python3 count()方法
描述:count() 方法用於統計字符串里某個字符出現的次數。可選參數為在字符串搜索的開始與結束位置。
語法:str.count(sub, start= 0,end=len(string))
參數:
- sub -- 搜索的子字符串
- start -- 字符串開始搜索的位置。默認為第一個字符,第一個字符索引值為0。
- end -- 字符串中結束搜索的位置。字符中第一個字符的索引為 0。默認為字符串的最后一個位置。
返回值:該方法返回子字符串在字符串中出現的次數。
實例:
1 str="www.runoob.com" 2 sub='o' 3 print ("str.count('o') : ", str.count(sub)) 4 5 sub='run' 6 print ("str.count('run', 0, 10) : ", str.count(sub,0,10)) 7 8 9 # 輸出結果 10 str.count('o') : 3 11 str.count('run', 0, 10) : 1
5.方法:Python3 strip()方法
描述:Python strip() 方法用於移除字符串頭尾指定的字符(默認為空格)。
語法:str.strip([chars]);
參數:
- chars -- 移除字符串頭尾指定的字符。
返回值:返回移除字符串頭尾指定的字符生成的新字符串。
實例:
1 str = "*****this is string example....wow!!!*****" 2 print (str.strip( '*' )) 3 4 5 # 輸出結果 6 this is string example....wow!!!
6.方法:Python3 split()方法
描述:split()通過指定分隔符對字符串進行切片,如果參數num 有指定值,則僅分隔 num 個子字符串
語法:str.split(str="", num=string.count(str))
參數:
- str -- 分隔符,默認為所有的空字符,包括空格、換行(\n)、制表符(\t)等。
- num -- 分割次數。
返回值:返回分割后的字符串列表。
實例:
1 str = "this is string example....wow!!!" 2 print (str.split( )) 3 print (str.split('i',1)) 4 print (str.split('w')) 5 6 7 # 輸出結果 8 ['this', 'is', 'string', 'example....wow!!!'] 9 ['th', 's is string example....wow!!!'] 10 ['this is string example....', 'o', '!!!']
7.方法:Python3 center()方法
描述:center() 方法返回一個指定的寬度 width 居中的字符串,fillchar 為填充的字符,默認為空格。
語法:str.center(width[, fillchar])
參數:
- width -- 字符串的總寬度。
- fillchar -- 填充字符。
返回值:返回一個指定的寬度 width 居中的字符串,如果 width 小於字符串寬度直接返回字符串,否則使用 fillchar 去填充。
實例:
1 str = "[www.runoob.com]" 2 3 print ("str.center(40, '*') : ", str.center(40, '*')) 4 5 6 # 輸出結果 7 str.center(40, '*') : ************[www.runoob.com]************
8.方法:Python3 join()方法
描述:Python join() 方法用於將序列中的元素以指定的字符連接生成一個新的字符串。
語法:str.join(sequence)
參數:
- sequence -- 要連接的元素序列。
返回值:返回通過指定字符連接序列中元素后生成的新字符串。
實例:
1 s1 = "-" 2 s2 = "" 3 seq = ("r", "u", "n", "o", "o", "b") # 字符串序列 4 print (s1.join( seq )) 5 print (s2.join( seq )) 6 7 8 # 輸出結果 9 r-u-n-o-o-b 10 runoob
9.方法:Python3 maketrans()方法
描述:
- maketrans() 方法用於創建字符映射的轉換表,對於接受兩個參數的最簡單的調用方式,第一個參數是字符串,表示需要轉換的字符,第二個參數也是字符串表示轉換的目標。
- 兩個字符串的長度必須相同,為一一對應的關系。
注:Python3.4已經沒有string.maketrans()了,取而代之的是內建函數: bytearray.maketrans()、bytes.maketrans()、str.maketrans()
語法:str.maketrans(intab, outtab)
參數:
- intab -- 字符串中要替代的字符組成的字符串。
- outtab -- 相應的映射字符的字符串。
返回值:返回字符串轉換后生成的新字符串。
實例:
1 intab = "aeiou" 2 outtab = "12345" 3 trantab = str.maketrans(intab, outtab) 4 5 str = "this is string example....wow!!!" 6 print (str.translate(trantab)) 7 8 9 # 輸出結果 10 th3s 3s str3ng 2x1mpl2....w4w!!!
10.方法:Python3 translate()方法
描述:translate() 方法根據參數table給出的表(包含 256 個字符)轉換字符串的字符,要過濾掉的字符放到 deletechars參數中。
語法:
- str.translate(table[, deletechars]);
- bytes.translate(table[, delete])
- bytearray.translate(table[, delete])
參數:
- table -- 翻譯表,翻譯表是通過 maketrans() 方法轉換而來。
- deletechars -- 字符串中要過濾的字符列表。
返回值:返回翻譯后的字符串,若給出了 delete 參數,則將原來的bytes中的屬於delete的字符刪除,剩下的字符要按照table中給出的映射來進行映射 。
實例:
實例(Python 3.0+)
1 intab = "aeiou" 2 outtab = "12345" 3 trantab = str.maketrans(intab, outtab) # 制作翻譯表 4 5 str = "this is string example....wow!!!" 6 print (str.translate(trantab)) 7 8 9 # 輸出結果 10 th3s 3s str3ng 2x1mpl2....w4w!!!
實例:演示過濾掉字符'o'
1 # 制作翻譯表 2 bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') 3 4 # 轉換為大寫,並刪除字母o 5 print(b'runoob'.translate(bytes_tabtrans, b'o')) 6 7 8 # 輸出結果 9 b'RUNB'
11.方法:Python format 格式化函數
描述:
- Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
- 基本語法是通過 {} 和 : 來代替以前的 % 。
- format 函數可以接受不限個參數,位置可以不按順序。
實例
1 >>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序 2 'hello world' 3 4 >>> "{0} {1}".format("hello", "world") # 設置指定位置 5 'hello world' 6 7 >>> "{1} {0} {1}".format("hello", "world") # 設置指定位置 8 'world hello world' 9 10 >>>
也可以設置參數:
實例
1 # -*- coding: UTF-8 -*- 2 3 print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com")) 4 5 # 通過字典設置參數 6 site = {"name": "菜鳥教程", "url": "www.runoob.com"} 7 print("網站名:{name}, 地址 {url}".format(**site)) 8 9 # 通過列表索引設置參數 10 my_list = ['菜鳥教程', 'www.runoob.com'] 11 print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的 12 13 14 # 輸出結果 15 網站名:菜鳥教程, 地址 www.runoob.com 16 網站名:菜鳥教程, 地址 www.runoob.com 17 網站名:菜鳥教程, 地址 www.runoob.com
也可以向str.format() 傳入對象:
實例
1 # -*- coding: UTF-8 -*- 2 3 class AssignValue(object): 4 def __init__(self, value): 5 self.value = value 6 my_value = AssignValue(6) 7 print('value 為: {0.value}'.format(my_value)) # "0" 是可選的 8 9 10 # 輸出結果 11 value 為: 6
數字格式化
下表展示了 str.format() 格式化數字的多種方法:
1 >>> print("{:.2f}".format(3.1415926)); 2 3.14
| 數字 | 格式 | 輸出 | 描述 |
|---|---|---|---|
| 3.1415926 | {:.2f} | 3.14 | 保留小數點后兩位 |
| 3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數點后兩位 |
| -1 | {:+.2f} | -1.00 | 帶符號保留小數點后兩位 |
| 2.71828 | {:.0f} | 3 | 不帶小數 |
| 5 | {:0>2d} | 05 | 數字補零 (填充左邊, 寬度為2) |
| 5 | {:x<4d} | 5xxx | 數字補x (填充右邊, 寬度為4) |
| 10 | {:x<4d} | 10xx | 數字補x (填充右邊, 寬度為4) |
| 1000000 | {:,} | 1,000,000 | 以逗號分隔的數字格式 |
| 0.25 | {:.2%} | 25.00% | 百分比格式 |
| 1000000000 | {:.2e} | 1.00e+09 | 指數記法 |
| 13 | {:10d} | 13 | 右對齊 (默認, 寬度為10) |
| 13 | {:<10d} | 13 | 左對齊 (寬度為10) |
| 13 | {:^10d} | 13 | 中間對齊 (寬度為10) |
| 11 |
'{:b}'.format(11) '{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11) '{:#x}'.format(11) '{:#X}'.format(11) |
1011
11
13
b
0xb
0XB
|
進制 |
- ^, <, > 分別是居中、左對齊、右對齊,后面帶寬度, : 號后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。
- + 表示在正數前顯示 +,負數前顯示 -; (空格)表示在正數前加空格
- b、d、o、x 分別是二進制、十進制、八進制、十六進制。
此外我們可以使用大括號 {} 來轉義大括號,如下實例:
實例
1 # -*- coding: UTF-8 -*- 2 3 print ("{} 對應的位置是 {{0}}".format("runoob")) 4 5 6 # 輸出結果 7 runoob 對應的位置是 {0}
以上內容摘至菜鳥教程,為學習Python中字符串常用內建函數的學習筆記,僅供參考,如存在錯誤請指出,萬分感謝!
以上僅為Python中字符串部分常用內建函數,更多字符串內建函數請參閱菜鳥教程-http://www.runoob.com/python3/python3-string.html
