整理自python基礎|菜鳥教程 感謝菜鳥教程提供的優質資源!
1.capitalize()
将字元串的第一個字元轉換為大寫
執行個體
以下執行個體展示了capitalize()方法的執行個體:
#!/usr/bin/python3
str = "this is string example from runoob....wow!!!"
print ("str.capitalize() : ", str.capitalize())
以上執行個體輸出結果如下:
str.capitalize() : This is string example from runoob....wow!!!
2.center(width, fillchar)
傳回一個指定的寬度 width 居中的字元串,fillchar 為填充的字元,預設為空格。
以下執行個體展示了center()方法的執行個體:
#!/usr/bin/python3
str = "[www.runoob.com]"
print ("str.center(40, '*') : ", str.center(40, '*'))
以上執行個體輸出結果如下:
str.center(40, '*') : ************[www.runoob.com]************
3.count(str, beg= 0,end=len(string))
傳回 str 在 string 裡面出現的次數,如果 beg 或者 end 指定則傳回指定範圍内 str 出現的次數
以下執行個體展示了count()方法的執行個體:
#!/usr/bin/python3
str="www.runoob.com"
sub='o'
print ("str.count('o') : ", str.count(sub))
sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
以上執行個體輸出結果如下:
str.count('o') : 3
str.count('run', 0, 10) : 1
4.bytes.decode(encoding="utf-8", errors="strict")
Python3 中沒有 decode 方法,但我們可以使用 bytes 對象的 decode() 方法來解碼給定的 bytes 對象,這個 bytes 對象可以由 str.encode() 來編碼傳回。
#!/usr/bin/python3
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'))
以上執行個體輸出結果如下:
菜鳥教程
UTF-8 編碼: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 編碼: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解碼: 菜鳥教程
GBK 解碼: 菜鳥教程
5.encode(encoding='UTF-8',errors='strict')
以 encoding 指定的編碼格式編碼字元串,如果出錯預設報一個ValueError 的異常,除非 errors 指定的是'ignore'或者'replace'
#!/usr/bin/python3
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'))
以上執行個體輸出結果如下:
菜鳥教程
UTF-8 編碼: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 編碼: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解碼: 菜鳥教程
GBK 解碼: 菜鳥教程
6.endswith(suffix, beg=0, end=len(string))
檢查字元串是否以 obj 結束,如果beg 或者 end 指定則檢查指定的範圍内是否以 obj 結束,如果是,傳回 True,否則傳回 False.
#!/usr/bin/python3
Str='Runoob example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='run'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
以上執行個體輸出結果如下:
True
True
False
False
7.expandtabs(tabsize=8)
把字元串 string 中的 tab 符号轉為空格,tab 符号預設的空格數是 8 。
#!/usr/bin/python3
str = "this is\tstring example....wow!!!"
print ("原始字元串: " + str)
print ("替換 \\t 符号: " + str.expandtabs())
print ("使用16個空格替換 \\t 符号: " + str.expandtabs(16))
以上執行個體輸出結果如下:
原始字元串: this is string example....wow!!!
替換 \t 符号: this is string example....wow!!!
使用16個空格替換 \t 符号: this is string example....wow!!!
8.find(str, beg=0 end=len(string))
檢測 str 是否包含在字元串中,如果指定範圍 beg 和 end ,則檢查是否包含在指定範圍内,如果包含傳回開始的索引值,否則傳回-1
#!/usr/bin/python3
str1 = "Runoob example....wow!!!"
str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))
以上執行個體輸出結果如下:
7
7
-1
9.index(str, beg=0, end=len(string))
跟find()方法一樣,隻不過如果str不在字元串中會報一個異常.
#!/usr/bin/python3str1="Runoob example....wow!!!"str2="exam";print(str1.index(str2))print(str1.index(str2,5))print(str1.index(str2,10))
以上執行個體輸出結果如下(未發現的會出現異常資訊):
77Traceback(most recent calllast):File"test.py",line8,inprint(str1.index(str2,10))ValueError:substringnotfound
10.isalnum()
如果字元串至少有一個字元并且所有字元都是字母或數字則返 回 True,否則傳回 False
#!/usr/bin/python3
str = "runoob2016" # 字元串沒有空格
print (str.isalnum())
str = "www.runoob.com"
print (str.isalnum())
以上執行個體輸出結果如下:
True
False
11.isalpha()
如果字元串至少有一個字元并且所有字元都是字母則傳回 True, 否則傳回 False
#!/usr/bin/python3
str = "runoob"
print (str.isalpha())
str = "Runoob example....wow!!!"
print (str.isalpha())
以上執行個體輸出結果如下:
True
False
12.isdigit()
如果字元串隻包含數字則傳回 True 否則傳回 False..
#!/usr/bin/python3
str = "123456";
print (str.isdigit())
str = "Runoob example....wow!!!"
print (str.isdigit())
以上執行個體輸出結果如下:
True
False
13.islower()
如果字元串中包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是小寫,則傳回 True,否則傳回 False
#!/usr/bin/python3
str = "RUNOOB example....wow!!!"
print (str.islower())
str = "runoob example....wow!!!"
print (str.islower())
以上執行個體輸出結果如下:
False
True
14.isnumeric()
如果字元串中隻包含數字字元,則傳回 True,否則傳回 False
#!/usr/bin/python3
str = "runoob2016"
print (str.isnumeric())
str = "23443434"
print (str.isnumeric())
以上執行個體輸出結果如下:
False
True
15.isspace()
如果字元串中隻包含空白,則傳回 True,否則傳回 False.
#!/usr/bin/python3
str = " "
print (str.isspace())
str = "Runoob example....wow!!!"
print (str.isspace())
以上執行個體輸出結果如下:
True
False
16.istitle()
如果字元串是标題化的(見 title())則傳回 True,否則傳回 False
#!/usr/bin/python3
str = "This Is String Example...Wow!!!"
print (str.istitle())
str = "This is string example....wow!!!"
print (str.istitle())
以上執行個體輸出結果如下:
True
False
17.isupper()
如果字元串中包含至少一個區分大小寫的字元,并且所有這些(區分大小寫的)字元都是大寫,則傳回 True,否則傳回 False
#!/usr/bin/python3
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())
以上執行個體輸出結果如下:
True
False
18.join(seq)
以指定字元串作為分隔符,将 seq 中所有的元素(的字元串表示)合并為一個新的字元串
#!/usr/bin/python3
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字元串序列
print (s1.join( seq ))
print (s2.join( seq ))
以上執行個體輸出結果如下:
r-u-n-o-o-b
runoob
19.len(string)
傳回字元串長度
以下執行個體展示了 len() 的使用方法:
>>>str = "runoob"
>>> len(str) # 字元串長度
6
>>> l = [1,2,3,4,5]
>>> len(l) # 清單元素個數
5
20.ljust(width[, fillchar])
傳回一個原字元串左對齊,并使用 fillchar 填充至長度 width 的新字元串,fillchar 預設為空格。
#!/usr/bin/python3
str = "Runoob example....wow!!!"
print (str.ljust(50, '*'))
以上執行個體輸出結果如下:
Runoob example....wow!!!**************************
21.lower()
轉換字元串中所有大寫字元為小寫.
#!/usr/bin/python3
str = "Runoob EXAMPLE....WOW!!!"
print( str.lower() )
以上執行個體輸出結果如下:
runoob example....wow!!!
22.lstrip()
截掉字元串左邊的空格或指定字元。
#!/usr/bin/python3
str = " this is string example....wow!!! ";
print( str.lstrip() );
str = "88888888this is string example....wow!!!8888888";
print( str.lstrip('8') );
以上執行個體輸出結果如下:
this is string example....wow!!!
this is string example....wow!!!8888888
23.maketrans()
建立字元映射的轉換表,對于接受兩個參數的最簡單的調用方式,第一個參數是字元串,表示需要轉換的字元,第二個參數也是字元串表示轉換的目标。
#!/usr/bin/python3
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print (str.translate(trantab))
以上執行個體輸出結果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
24.max(str)
傳回字元串 str 中最大的字母。
#!/usr/bin/python3
str = "runoob"
print ("最大字元: " + max(str))
以上執行個體輸出結果如下:
最大字元: u
25.min(str)
傳回字元串 str 中最小的字母。
#!/usr/bin/python3
str = "runoob";
print ("最小字元: " + min(str));
以上執行個體輸出結果如下:
最小字元: b
26.replace(old, new [, max])
把 将字元串中的 str1 替換成 str2,如果 max 指定,則替換不超過 max 次。
#!/usr/bin/python3
str = "www.w3cschool.cc"
print ("菜鳥教程新位址:", str)
print ("菜鳥教程新位址:", str.replace("w3cschool.cc", "runoob.com"))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
以上執行個體輸出結果如下:
菜鳥教程新位址: www.w3cschool.cc
菜鳥教程新位址: www.runoob.com
thwas was string example....wow!!!
27.rfind(str, beg=0,end=len(string))
類似于 find()函數,不過是從右邊開始查找.
#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))
print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))
以上執行個體輸出結果如下:
5
5
-1
2
2
-1
28.rindex( str, beg=0, end=len(string))
類似于 index(),不過是從右邊開始.
#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.rindex(str2,10))
以上執行個體輸出結果如下:
5
Traceback (most recent call last):
File "test.py", line 6, in
print (str1.rindex(str2,10))
ValueError: substring not found
29.rjust(width,[, fillchar])
傳回一個原字元串右對齊,并使用fillchar(預設空格)填充至長度 width 的新字元串
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.rjust(50, '*'))
以上執行個體輸出結果如下:
******************this is string example....wow!!!
30.rstrip()
删除字元串字元串末尾的空格.
#!/usr/bin/python3
str = " this is string example....wow!!! "
print (str.rstrip())
str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))
以上執行個體輸出結果如下:
this is string example....wow!!!
*****this is string example....wow!!!
31.split(str="", num=string.count(str))
num=string.count(str)) 以 str 為分隔符截取字元串,如果 num 有指定值,則僅截取 num 個子字元串
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))
以上執行個體輸出結果如下:
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
32.splitlines([keepends])
按照行('\r', '\r\n', \n')分隔,傳回一個包含各行作為元素的清單,如果參數 keepends 為 False,不包含換行符,如果為 True,則保留換行符。
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
>>>
33.startswith(str, beg=0,end=len(string))
檢查字元串是否是以 obj 開頭,是則傳回 True,否則傳回 False。如果beg 和 end 指定值,則在指定範圍内檢查。
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))
以上執行個體輸出結果如下:
True
True
False
34.strip([chars])
在字元串上執行 lstrip()和 rstrip()
#!/usr/bin/python3
str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))
以上執行個體輸出結果如下:
this is string example....wow!!!
35.swapcase()
将字元串中大寫轉換為小寫,小寫轉換為大寫
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.swapcase())
str = "This Is String Example....WOW!!!"
print (str.swapcase())
以上執行個體輸出結果如下:
THIS IS STRING EXAMPLE....WOW!!!
tHIS iS sTRING eXAMPLE....wow!!!
36.title()
傳回"标題化"的字元串,就是說所有單詞都是以大寫開始,其餘字母均為小寫(見 istitle())
#!/usr/bin/python
str = "this is string example from runoob....wow!!!"
print (str.title())
以上執行個體輸出結果如下:
This Is String Example From Runoob....Wow!!!
37.translate(table, deletechars="")
根據 str 給出的表(包含 256 個字元)轉換 string 的字元, 要過濾掉的字元放到 deletechars 參數中
#!/usr/bin/python3
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # 制作翻譯表
str = "this is string example....wow!!!"
print (str.translate(trantab))
以上執行個體輸出結果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
38.upper()
轉換字元串中的小寫字母為大寫
#!/usr/bin/python3
str = "this is string example from runoob....wow!!!";
print ("str.upper() : ", str.upper())
以上執行個體輸出結果如下:
str.upper() : THIS IS STRING EXAMPLE FROM RUNOOB....WOW!!!
39.zfill (width)
傳回長度為 width 的字元串,原字元串右對齊,前面填充0
#!/usr/bin/python3
str = "this is string example from runoob....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))
以上執行個體輸出結果如下:
str.zfill : this is string example from runoob....wow!!!
str.zfill : 000000this is string example from runoob....wow!!!
40.isdecimal()
檢查字元串是否隻包含十進制字元,如果是傳回 true,否則傳回 false。
#!/usr/bin/python3str="runoob2016"print(str.isdecimal())str="23443434"print(str.isdecimal())
以上執行個體輸出結果如下:
FalseTrue