字符串屬於序列類型,根據字符串內容的多少可以將字符串分為單行字符串和多行字符串。其中單行字符串可以由一對雙引號(" ")或一對單引號(' ')表示,單引號和雙引號等效。多行字符串可由一對三單引號(''' ''')或一對三雙引號(""" """)表示,三單引號和三雙引號也等效。
1. capitalize()函數
描述:將字符串的第一個字母變成大寫,其餘字母變為小寫。
語法:str.capitalize() —> str 返回字符串
程序示例:str1 = "i Love python"
str2 = " i Love python"
str3 = "I Love python"
print(str1.capitalize())
print(str2.capitalize())
print(str3.capitalize())
程序運行結果:I love python
i love python
I love python
2. title()函數描述:返回一個滿足標題格式的字符串。即所有英文單詞首字母大寫,其餘英文字母小寫。
語法:str.title() -> str 返回一個字符串
程序示例:str = "i love python"
print(str.title())
程序運行結果:I Love Python3. swapcase()函數描述:將字符串str中的大小寫字母同時進行互換。即將字符串str中的大寫字母轉換為小寫字母,將小寫字母轉換為大寫字母。
語法:str.swapcase() -> str 返回字符串
程序示例:str1="I Love PYTHON"
str2="我愛python Python pYTHON"
print(str1.swapcase())
print(str2.swapcase())
程序運行結果:i lOVE python
我愛PYTHON pYTHON Python
4. lower()函數描述:將字符串中的所有大寫字母轉換為小寫字母。
語法:str.lower() -> str 返回字符串
程序示例:str1 = "I Love Python"
str2 = "Groß - α"
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())
程序運行結果:i love python
i love python
gross - α
groß - α
注意 lower()函數和casefold()函數的區別:
lower() 方法只對ASCII編碼,即『A-Z』有效,對於其它語言中把大寫轉換為小寫的情況無效,只能用 casefold() 函數。
5. upper()函數描述:將字符串中的所有小寫字母轉換為大寫字母。
語法:str.upper() -> str 返回字符串
程序示例:str1 = "i love python"
str2 = "I Love Python"
print(str1.upper())
print(str2.upper())
程序運行結果:I LOVE PYTHON
I LOVE PYTHON
6. casefold()函數描述:將字符串中的所有大寫字母轉換為小寫字母。也可以將非英文 語言中的大寫轉換為小寫。
注意 lower()函數和casefold()函數的區別:lower() 方法只對ASCII編碼,即『A-Z』有效,對於其它語言中把大寫轉換為小寫的情況無效,只能用 casefold() 函數。
語法:str.casefold() -> str 返回字符串
程序示例:str1 = "I Love Python"
str2 = "Groß - α" #德語 大寫α
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())
程序運行結果:i love python
i love python
gross - α
groß - α
解決字符串填充問題:7. center()函數描述:返回一個長度為width,兩邊用fillchar(單字符)填充的字符串,即字符串str居中,兩邊用fillchar填充。若字符串的長度大於width,則直接返回字符串str。
語法:str.center(width , "fillchar") -> str 返回字符串 注意:引號不可省
程序示例:str = "i love python"
print(str.center(20,"*"))
print(str.center(1,"*"))
print(str.center(20,"8"))
print(str.center(20))
程序運行結果:***i love python****
i love python
888i love python8888
i love python
8. ljust()函數描述:返回一個原字符串左對齊,並使用fillchar填充(默認為空格)至指定長度的新字符串。如果指定的長度小於原字符串的長度則返回原字符串。
語法:str.ljust(width, fillchar) -> str 返回一個新的字符串
程序示例:str = "python"
print(str.ljust(30,"*"))
print(str.ljust(30))
print(str.ljust(30),"1")
程序運行結果:python************************
python
python 1
9. rjust()函數描述:返回一個原字符串右對齊,並使用fillchar填充(默認為空格)至指定長度的新字符串。如果指定的長度小於原字符串的長度則返回原字符串。
語法:str.ljust(width, fillchar) -> str 返回一個新的字符串
程序示例:str = "python"
print(str.rjust(30,"*"))
print(str.rjust(30))
print("1",str.rjust(30))
程序運行結果:************************python
python
1 python
10. zfill()函數描述:返回指定長度的字符串,使原字符串右對齊,前面用0填充到指定字符串長度。
語法:str.zfill(width) -> str 返回一個字符串
程序示例:str = "i love python"
print(str.zfill(30))
print(str.zfill(2))
print(str.zfill())
程序運行結果:i love python
Traceback (most recent call last):
File "D:/python/work/chaper01/字符串.py", line 10, in <module> print(str.zfill())
TypeError: zfill() takes exactly one argument (0 given)
解決統計字符次數問題:11. count()函數描述:統計字符串裡某個字符出現的次數。可以選擇字符串索引的起始位置和結束位置。
語法:str.count("char", start,end) 或 str.count("char") -> int 返回整數
str —— 為要統計的字符(可以是單字符,也可以是多字符)。
star —— 為索引字符串的起始位置,默認參數為0。
end —— 為索引字符串的結束位置,默認參數為字符串長度即len(str)。
程序示例:str = "i love python,i am learning python"
print(str.count("i"))
print(str.count("i",2))
print(str.count("i",2,5))
print(str.count("am"))
程序運行結果:3
2
0
1
解決編碼問題:12. encode()函數描述:以指定的編碼格式編碼字符串,默認編碼為 'utf-8'。
語法:str.encode(encoding='utf-8', errors='strict') -> bytes (獲得bytes類型對象)
encoding 參數可選,即要使用的編碼,默認編碼為 'utf-8'。字符串編碼常用類型有:utf-8,gb2312,cp936,gbk等。
errors 參數可選,設置不同錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個UnicodeEncodeError。其它可能值有 'ignore', 'replace', 'xmlcharrefreplace'以及通過 codecs.register_error() 註冊其它的值。
程序示例:str1 = "我愛祖國"str2 = "I love my country"print("utf8編碼:",str1.encode(encoding="utf8",errors="strict"))print("utf8編碼:",str2.encode(encoding="utf8",errors="strict"))print("gb2312編碼:",str1.encode(encoding="gb2312",errors="strict"))print("gb2312編碼:",str2.encode(encoding="gb2312",errors="strict"))print("cp936編碼:",str1.encode(encoding="cp936",errors="strict"))print("cp936編碼:",str2.encode(encoding="cp936",errors="strict"))print("gbk編碼:",str1.encode(encoding="gbk",errors="strict"))print("gbk編碼:",str2.encode(encoding="gbk",errors="strict"))
程序運行結果:utf8編碼:b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
utf8編碼:b'I love my country'
gb2312編碼:b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gb2312編碼:b'I love my country'
cp936編碼:b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
cp936編碼:b'I love my country'
gbk編碼:b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gbk編碼:b'I love my country'
13. decode()函數描述:以 encoding 指定的編碼格式解碼字符串,默認編碼為字符串編碼。
語法:str.decode(encoding='utf-8', errors='strict')
encoding ——要使用的編碼,如:utf-8,gb2312,cp936,gbk等。
errors ——設置不同解碼錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個 UnicodeDecodeError。其它可能得值有 'ignore', 'replace'以及通過 codecs.register_error() 註冊的1其它值。
程序示例:s = "我愛祖國"str1 = s.encode(encoding="utf-8",errors="strict")str2 = s.encode("gb2312")str3 = s.encode("gbk")print(str1.decode(encoding="utf-8",errors="strict"))print(str1.decode(encoding="gbk",errors="ignore"))print(str1.decode(encoding="gbk",errors="strict"))print(str1.decode(encoding="gbk",errors="replace"))print("\n")print(str2.decode("gb2312"))print(str3.decode("gbk"))程序運行結果:我愛祖國
鎴戠埍紲栧浗
鎴戠埍紲栧浗
鎴戠埍紲栧浗
我愛祖國
我愛祖國
註:在python3.x中,encode()函數只能用於字符串類型,而decode()函數只能用於字節數據類型。程序示例中 str1,str2,str3都是字節數據類型(通過encode()函數把 字符串類型s 轉換為字節數據類型)。
14. expandtabs()函數描述:返回一個字符串的副本。使原字符串中的制表符("\t")的使用空間變大。使用空格來擴展空間。
語法:str.expandtabs(tabsize=8) —> str 返回字符串
程序示例:str = "i love\tpython"
print(str.expandtabs())
print(str.expandtabs(tabsize=8))
print(str.expandtabs())
print(str.expandtabs(2))
print(str.expandtabs(tabsize=2))
print(str.expandtabs(tabsize=9))
print(str.expandtabs(tabsize=10))
程序運行結果:i love python
i love python
i love python
i love python
i love python
i love python
i love python
解決查找指定字符(子字符串)位置問題:15. find()函數描述:查找字符串中指定的子字符串sub第一次出現的位置,可以規定字符串的索引查找範圍。若無則返回 -1。
語法:str.find(sub,start,end) -> int 返回整數
程序示例:str = "i love python"
print(str.find("o"))
print(str.find("0",4))
print(str.find("o",4,12))
print(str.find(""))
print(str.find(" "))
print(str.find("k"))
程序運行結果:3
-1
11
0
1
-1
16. rfind()函數描述:查找字符串中指定的子字符串sub最後一次出現的位置,可以規定字符串的索引查找範圍。若無則返回 -1。
語法:str.rfind(sub,start,end) -> int 返回整數
註:rfind()函數用法與find()函數相似,rfind()函數返回指定子字符串最後一次出現的位置,find()函數返回指定子字符串第一次出現的位置。
程序示例:str = "i love python python"
print(str.rfind("o"))
print(str.rfind("o",11))
print(str.rfind("o",0,12))
print(str.rfind("python"))
print(str.rfind(""))
print(str.rfind(" "))
print(str.rfind("2"))
程序運行結果:18
18
11
14
20
13
-1
17. index()函數描述:查找字符串中第一次出現的子字符串的位置,可以規定字符串的索引查找範圍[star,end)。若無則會報錯。
語法:str.index(sub, start, end) -> int 返回整數
程序示例:str = "i love python"
print(str.index("o"))
print(str.index("o",4))
print(str.index("o",4,12))
print(str.index("love"))
print(str.index("k"))
程序運行結果:Traceback (most recent call last):
File "D:/python/work/chaper01/字符串.py", line 16, in <module>
print(str.index("k"))ValueError: substring not found
3
11
11
2
註:index()函數和find()函數類似,但index()函數沒有找到子字符串會報錯。
18. rindex()函數描述:查找字符串中最後一次出現的子字符串的位置,可以規定字符串的索引查找範圍[star,end),若無則會報錯。
語法:str.rindex(sub, start, end) -> int 返回整數。
註:rindex()函數用法與index()函數相似,rindex()函數返回指定子字符串最後一次出現的位置,index()函數返回指定子字符串第一次出現的位置。
程序示例:str = "i love python python"
print(str.rindex("p"))
print(str.rindex("o",5))
print(str.rindex("o",5,13))
print(str.rindex("python"))
print(str.rindex("k"))
len(str),str[5:13]
程序運行結果:14
18
11
14
Traceback (most recent call last):
File "D:/python/work/chaper01/字符串.py", line 16, in <module>
print(str.rindex("k"))ValueError: substring not found
解決判斷問題(返回bool類型)21. endswith()函數描述:判斷字符串是否以指定字符或子字符串結尾。
語法:str.endswith("suffix", start, end) 或
str[start,end].endswith("suffix") 用於判斷字符串中某段字符串是否以指定字符或子字符串結尾。
—> bool 返回值為布爾類型(True,False)
注意:空字符的情況。返回值通常為True
程序示例:str = "i love python"
print("1:",str.endswith("n"))
print("2:",str.endswith("python"))
print("3:",str.endswith("n",0,6))
print("4:",str.endswith(""))
print("5:",str[0:6].endswith("n"))
print("6:",str[0:6].endswith("e"))
print("7:",str[0:6].endswith(""))
print("8:",str.endswith(("n","z")))
print("9:",str.endswith(("k","m")))
file = "python.txt"
if file.endswith("txt"):
print("該文件是文本文件")
elif file.endswith(("AVI","WMV","RM")):
print("該文件為視頻文件")
else:
print("文件格式未知")
程序運行結果:1: True
2: True
3: False
4: True
5: False
6: True
7: True
8: True
9: False
該文件是文本文件
22. startswith()函數
描述:判斷字符串是否以指定字符或子字符串開頭。
語法:str.endswith("suffix", start, end) 或
str[start,end].endswith("suffix") 用於判斷字符串中某段字符串是否以指定字符或子字符串結尾。
—> bool 返回值為布爾類型(True,False)
注意:空字符的情況。返回值通常也為True
程序示例:str = "hello,i love python"
print("1:",str.startswith("h"))
print("2:",str.startswith("l",2,10))
print("3:",str.startswith(""))
print("4:",str[0:6].startswith("h"))
print("5:",str[0:6].startswith("e"))
print("6:",str[0:6].startswith(""))
print("7:",str.startswith(("h","z")))
print("8:",str.startswith(("k","m")))
程序運行結果:1: True
2: True
3: True
4: True
5: False
6: True
7: True
8: False
23. isalnum()函數描述:檢測字符串是否由字母和數字組成。
語法:str.isalnum() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "i love python 666"
str2 = "python" #全為字母
str3 = "123" #全為數字
str4 = "python666"
print(str1.isalnum())
print(str2.isalnum())
print(str3.isalnum())
print(str4.isalnum())
程序運行結果:False
True
True
True
24. isalpha()函數描述:檢測字符串是否只由字母組成。
語法:str.isalpha() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "python" #全為字母
str2 = " python" #存在空格
str3 = "123" #全為數字
str4 = "python666"
print(str1.isalpha())
print(str2.isalpha())
print(str3.isalpha())
print(str4.isalpha()
程序運行結果:True
False
False
False
25. isdecimal()函數描述:檢查字符串是否只包含十進位字符。該方法只存在於unicode對象中。
注意:定義一個十進位字符串,只需要在字符串前添加前綴 'u' 即可。
語法:str.isdecimal() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = u"123456"
str2 = u"python666"
str3 = "123456"
str4 = "python666"
print(str1.isdecimal())
print(str2.isdecimal())
print(str3.isdecimal())
print(str4.isdecimal())
程序運行結果:True
False
True
False
26. isdigit()函數描述:檢測字符串是否只由數字組成.
語法:str.isdigit() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "python" #全為字母
str2 = " python" #存在空格
str3 = "123" #全為數字
str4 = "python666"
str5 = "一二三四五六七"
str6 = "①"
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
print(str4.isdigit())
print(str5.isdigit())
print(str6.isdigit())
程序運行結果:False
False
True
False
False
True
27. isidentifier()函數描述:判斷str是否是有效的標識符。str為符合命名規則的變量,保留標識符則返回True,否者返回False。
語法:str.isidentifier() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "123" #變量名為123
str2 = "def" #變量名為保留字
str3 = "_123" #變量名有下劃線開頭
str4 = "student"#變量名由字母開端
print(str1.isidentifier())
print(str2.isidentifier())
print(str3.isidentifier())
print(str4.isidentifier())
程序運行結果:False
True
True
True
28. islower()函數描述:檢測字符串中的字母是否全由小寫字母組成。(字符串中可包含非字母字符)
語法:str.islower() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "i love python"
str2 = "我愛python!"
str3 = "I love python"
print(str1.islower())
print(str2.islower())
print(str3.islower())
程序運行結果:True
True
False
29. isupper()函數描述:檢測字符串中的字母是否全由大寫字母組成。(字符串中可包含非字母字符)。
語法:str.isupper() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "I LOVE PYTHON" #全為大寫字母
str2 = "i LOVE PYTHON" #存在小寫字母
str3 = "我愛PYTHON" #存在非字母的字符
print(str1.isupper())
print(str2.isupper())
print(str3.isupper())
程序運行結果:True
False
True
30. isnumeric()函數描述:測字符串是否只由數字組成。這種方法是只適用於unicode對象。
註:把一個字符串定義為Unicode,只需要在字符串前添加 前綴 'u'
語法:str.isnumeric() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = u"123456" #全為數字
str2 = "123456"
str3 = "python666" #字母數字組合
str4 = "一二三四五六" #中文數字
str5 = "①"
print(str1.isnumeric())
print(str2.isnumeric())
print(str3.isnumeric())
print(str4.isnumeric())
print(str5.isnumeric())
程序運行結果:True
True
False
True
True
31. isprintable()函數描述:判斷字符串中是否有列印後不可見的內容。如:\n \t 等字符。
語法: str.isprintable() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "i love python"
str2 = "i love python \n"
str3 = "i love \t python"
print(str1.isprintable())
print(str2.isprintable())
print(str3.isprintable())
程序運行結果:True
False
False
32. isspace()函數描述: 檢測字符串是否只由空格組成。
語法:str.isspace() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = " "#空格
str2 = "i love python"
print(str1.isspace())
print(str2.isspace())
print(str2[1].isspace())
程序運行結果:True
False
True
33. istitle()函數描述:檢測判斷字符串中所有單詞的首字母是否為大寫,且其它字母是否為小寫,字符串中可以存在其它非字母的字符。
語法:str.istitle() -> bool 返回值為布爾類型(True,False)
程序示例:str1 = "I Love Python"
str2 = "I love python"
str3 = "I LOVE PYTHON"
str4 = "我愛Python"
print(str1.istitle())
print(str2.istitle())
print(str3.istitle())
print(str4.istitle())
程序運行結果:True
False
False
True
解決字符串兩端:34. strip()函數描述:從字符串str中去掉在其左右兩邊chars中列出的字符。
註:chars傳入的是一個字符數組,編譯器去除兩端所有相應的字符,直到出現第一個在chars中不匹配的字符。詳看示例。
語法:str.strip(chars) -> str 返回一個新的字符串
程序示例:str = "123456789321"
print(str.strip("123"))
str1 = "my name is ymyyyy"
print(str1.strip("my"))
print(str1.strip("my "))
程序運行結果:456789
name is
name is
35. lstrip()函數描述:從字符串str中去掉在其左邊chars中列出的字符。
註:chars傳入的是一個字符數組,編譯器去除兩端所有相應的字符,直到出現第一個在chars中不匹配的字符。詳看示例。
語法:str.lstrip(chars) -> str 返回一個新的字符串
程序示例:str1 = "bacjabck123kluabc"
print(str1.lstrip("abc"))
str2 = "12578asdfgh12"
print(str2.lstrip("12"))
程序運行結果:jabck123kluabc
578asdfgh12
36. rstrip()函數描述:從字符串str中去掉在其右邊chars中列出的字符。
註:chars傳入的是一個字符數組,編譯器去除兩端所有相應的字符,直到出現第一個在chars中不匹配的字符。詳看示例。
語法:str.rstrip(chars) -> str 返回一個新的字符串
程序示例:str1 = "abcjabck123kluabcca"
print(str1.rstrip("abc"))
str2 = "12578asdfgh11112"
print(str2.rstrip("12"))
程序運行結果:abcjabck123klu
12578asdfgh
解決 制表 翻譯 問題:37. maketrans()函數描述:製作翻譯表,刪除表,常與translate()函數連用。即:返回用於str.translate()函數翻譯的的轉換表。
語法:maketrans(x, y=None, z=None, /) 返回可用於str.translate()函數的轉換表
str.maketrans(x,y,z)
bytes.maketrans(x,y)
bytearray.maketrans(x,y)
如果只有一個參數x,它必須是一個字典且為Unicode形式的映射。
如果有兩個參數x和y,它們必須是長度相等的字符串,並且在結果映射中,x中的每個字符都將映射到y中相同位置的字符(Unicode形式的映射)。
如果有三個參數x,y和z. x和y用法同上,z為指定要刪除的字符串,其結果中的字符將一一映射為:None。
bytes.maketrans(x,y) 和 bytearray.maketrans(x,y) 必須要有x和y兩個參數。
str.maketrans(x,y,z)形式:程序示例:
註:z的長度可以和x和y不同。s = "123456789"
#只有參數x,且x為字典。
map1 = str.maketrans({"1":"a","2":"b","3":"c"})
print(map1,type(map1),ord("1"),ord("2"),ord("3"))
map2 = str.maketrans("123","abc")
print(map2,type(map2),ord("a"),ord("b"),ord("c"))
map3 = str.maketrans("123","abc","56k")
print(map3,type(map3),ord("5"),ord("6"),ord("k"))
程序運行結果:49: 'a', 50: 'b', 51: 'c'} <class 'dict'> 49 50 51
{49: 97, 50: 98, 51: 99} <class 'dict'> 97 98 99
{49: 97, 50: 98, 51: 99, 53: None, 54: None, 107: None} <class 'dict'> 53 54 107 In [6]:
bytes.maketrans(x,y)形式:程序示例:map4 = bytes.maketrans(b"123",b"abc")
print(type(b"123"),type(b"abc"),type(map4),map4)
程序運行結果:<class 'bytes'> <class 'bytes'> <class 'bytes'>
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0abc456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
bytearray.maketrans(x,y)形式:程序示例:map5 = bytearray.maketrans(b"123",b"abc")
print(type(b"123"),type(b"abc"),type(map5),map5)
程序運行結果:<class 'bytes'> <class 'bytes'> <class 'bytes'>
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0abc456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
38.0 translate()函數描述:過濾(刪除),翻譯字符串。即根據maketrans()函數給出的字符映射轉換表來轉換字符串中的字符。
註:translate()函數是先過濾(刪除),再根據maketrans()函數返回的轉換表來翻譯。
語法:str.translate(table) -> str 返回一個字符串
str.translate(table)
bytes.translate(table, deletechars)
bytearray.translate(table, deletechars)
程序示例:s = "123456789abc"
程序運行結果:
s1 = b"123456789abc"
map1 = str.maketrans({"1":"a","2":"b","3":"c"})
print(map1,type(map1),ord("1"),ord("2"),ord("3"))
map2 = str.maketrans("123","abc")
print(map2,type(map2),ord("a"),ord("b"),ord("c"))
#有x,y,z三個參數
map3 = str.maketrans("123","abc","56k")
print(map3,type(map3),ord("5"),ord("6"),ord("k"))
map4 = bytes.maketrans(b"123",b"abc")
print(type(b"123"),type(b"abc"),type(map4),map4)
print("\n")
map5 = bytearray.maketrans(b"123",b"abc")
print(type(b"123"),type(b"abc"),type(map5),map5)
print("\n\n")
print(s.translate(map1))
print(s.translate(map2))
print(s.translate(map3))
print(s1.translate(map5))
print(s1.translate(map4,b"78b"))
print(s1.translate(map5,b"9")){49: 'a', 50: 'b', 51: 'c'} <class 'dict'> 49 50 51
{49: 97, 50: 98, 51: 99} <class 'dict'> 97 98 99
{49: 97, 50: 98, 51: 99, 53: None, 54: None, 107: None} <class 'dict'> 53 54 107
<class 'bytes'> <class 'bytes'> <class 'bytes'> b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0abc456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
<class 'bytes'> <class 'bytes'> <class 'bytes'> b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0abc456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
abc456789abc
abc456789abc
abc4789abc
b'abc456789abc'
b'abc4569ac'
b'abc45678abc'
解決分割字符串問題:39. partition()函數:描述:根據指定的分隔符(sep)將字符串進行分割。從字符串左邊開始索引分隔符sep,索引到則停止索引。
語法:str.partition(sep) -> (head, sep, tail) 返回一個三元元組,head:分隔符sep前的字符串,sep:分隔符本身,tail:分隔符sep後的字符串。
sep —— 指定的分隔符。
如果字符串包含指定的分隔符sep,則返回一個三元元組,第一個為分隔符sep左邊的子字符串,第二個為分隔符sep本身,第三個為分隔符sep右邊的子字符串。
如果字符串不包含指定的分隔符sep,仍然返回一個三元元組,第一個元素為字符串本身,第二第三個元素為空字符串
程序示例:str = "https://www.baidu.com/"
print(str.partition("://"))
print(str.partition(","))
print(str.partition("."))
print(type(str.partition("://")))
程序運行結果:('https', '://', 'www.baidu.com/')
('https://www.baidu.com/', '', '')
('https://www', '.', 'baidu.com/')
<class 'tuple'>
40. rpartition()函數描述:根據指定的分隔符(sep)將字符串進行分割。從字符串右邊(末尾)開始索引分隔符sep,索引到則停止索引。
語法:str.rpartition(sep) -> (head, sep, tail) 返回一個三元元組,head:分隔符sep前的字符串,sep:分隔符本身,tail:分隔符sep後的字符串。
sep —— 指定的分隔符。
如果字符串包含指定的分隔符sep,則返回一個三元元組,第一個為分隔符sep左邊的子字符串,第二個為分隔符sep本身,第三個為分隔符sep右邊的子字符串。
如果字符串不包含指定的分隔符sep,仍然返回一個三元元組,第一個元素為字符串本身,第二第三個元素為空字符串。
註:rpartition()函數與partition()函數用法相似,rpartition()函數從右邊(末尾)開始索引,partition()函數從左邊開始索引。
程序示例:str = "https://www.baidu.com/"
print(str.rpartition("://"))
print(str.rpartition(","))
print(str.rpartition("."))
print(type(str.partition("://")))
程序運行結果:('https', '://', 'www.baidu.com/')
('', '', 'https://www.baidu.com/')
('https://www.baidu', '.', 'com/')
<class 'tuple'>
41. split()函數描述:拆分字符串。通過指定分隔符sep對字符串進行分割,並返回分割後的字符串列表。
語法:str.split(sep=None, maxsplit=-1) -> list of strings 返回 字符串列表 或str.split(sep=None, maxsplit=-1)[n]
sep —— 分隔符,默認為空格,但不能為空即(")。
maxsplit —— 最大分割參數,默認參數為-1。
[n] —— 返回列表中下標為n的元素。列表索引的用法。
程序示例:str1 = "i love python"str2 = "https://www.baidu.com"
str3 = "script<i love python>script"
str4 = "i \n love \n python"
print(str1.split())
print(str2.split("."))
print(str2.split(".",-1))
print(str2.split(".",1))
print(str2.split(".")[1])
print(str3.split("<")[1].split(">")[0])
print(str4.split("\n"))
程序運行結果:['i', 'love', 'python']
['https://www', 'baidu', 'com']
['https://www', 'baidu', 'com']
['https://www', 'baidu.com']
baidu
i love python
['i ', ' love ', ' python']
42. rsplit()函數描述:拆分字符串。通過指定分隔符sep對字符串進行分割,並返回分割後的字符串列表,類似於split()函數,只不過 rsplit()函數是從字符串右邊(末尾)開始分割。
語法:str.rsplit(sep=None, maxsplit=-1) -> list of strings 返回 字符串列表 或str.rsplit(sep=None, maxsplit=-1)[n]
sep —— 分隔符,默認為空格,但不能為空即(")。
maxsplit —— 最大分割參數,默認參數為-1。
[n] —— 返回列表中下標為n的元素。列表索引的用法。
程序示例:str = "https://www.baidu.com"
print(str.rsplit()) #默認空格分割。
print(str.rsplit("."))
print(str.rsplit(".",1))
print(str.rsplit(".",1)[1])
程序運行結果:['https://www.baidu.com']
['https://www', 'baidu', 'com']
['https://www.baidu', 'com']
com
43. splitlines()函數描述:按照('\n', '\r', \r\n'等)分隔,返回一個包含各行作為元素的列表,默認不包含換行符。
語法:str.splitlines(keepends) -> list of strings 返回 字符串列表
程序示例:s1 = """i
love
python
"""
s2 = "i\nlove\npython\n" #與s1等效。
s3 = "123\n456\r789\r\nabc"
print(s1.splitlines(True))
print(s1.splitlines()) #keepends 默認為False
print(s1.splitlines(False))
print(s2.splitlines())
print(s3.splitlines())
程序運行結果:['i\n', 'love\n', 'python\n']
['i', 'love', 'python']
['i', 'love', 'python']
['i', 'love', 'python']
['123', '456', '789', 'abc']
44. join()函數描述:將iterable變量的每一個元素後增加一個str字符串。
語法:str.join(iterable) -> str 返回字符串 即:返回一個以str作為分隔符,將iterable中的各元素合併連接成一個新的字符串。
程序示例:#對列表進行操作
l = ["1","2","3"]
print(" ".join(l)) #以空格為分隔符
print(",".join(l)) #以逗號為分隔符
#對字符串進行操作
str = "python"
print(" ".join(str)) #以空格為分隔符
print(",".join(str)) #以逗號為分隔符
#對字典進行操作
d = {"a":1,"b":2,"c":3}
print(" ".join(d)) #以空格為分隔符
print(",".join(d)) #以逗號為分隔符
#對元組進行操作
s = ("1","2","3")
print(" ".join(s)) #以空格為分隔符
print(",".join(s)) #以逗號為分隔符
程序運行結果:1 2 3
1,2,3
p y t h o n
p,y,t,h,o,n
b c a
b,c,a
1 2 3
1,2,3
解決替換問題:45. replace()函數:描述:返回字符串str的副本,所有old子字符串被替換為new字符串。
語法:str.replace(old, new, count) -> str 返回字符串str的副本
程序示例:s = "i love python python "
print(s.replace("o","w"))
print(s.replace("o","w",2))
print(s.replace("python","c++"))
print(s.replace("python","c++",1))
程序運行結果:i lwve pythwn pythwn
i lwve pythwn python
i love c++ c++
i love c++ python