Python字符串函數用法大全

2021-02-19 優碼社區

序言:

字符串屬於序列類型,根據字符串內容的多少可以將字符串分為單行字符串和多行字符串。其中單行字符串可以由一對雙引號(" ")或一對單引號(' ')表示,單引號和雙引號等效。多行字符串可由一對三單引號(''' ''')或一對三雙引號(""" """)表示,三單引號和三雙引號也等效。

 

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 Python

3. 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兩個參數。
註:z的長度可以和x和y不同。

str.maketrans(x,y,z)形式:程序示例:

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

相關焦點

  • Python 基礎(字符串)
    字符串的兩種定義方式1、通過內置函數str()函數將其他數據類型轉化為字符串>>> a = str(1.345)>>> a'1.345'# 查看類型>>> type(a)str2、直接加引號定義
  • Hive函數大全(含例子)之字符串函數(String Functions)
    字符串函數 String Functionsascii(string str)返回結果: 返回字符串str首字母的十進位ascii碼返回類型: int返回結果: 拼接字符串,函數接受任意數量的輸入返回類型: stringselect concat('A', 'C', 'B'); -- 結果為 ACBselect concat
  • MySQL函數基礎——字符串函數詳解
    昨天,咱們對MySQL的數學函數進行了講解,今天,咱們再來解析MySQL字符串函數。字符串函數主要用來處理資料庫中的字符串數據,MySQL中字符串函數有:計算字符串長度函數、字符串合併函數、字符串替換函數、字符串比較函數、查找指定字符串位置函數等。
  • Python 格式化字符串,這個方法真的即絲滑又舒服!
    一堆堆的爛數據裡面有很多的字符串,所以最近老用到格式化字符串...按理說我應該對這種重複性的動作很煩,起初確實是這樣,但是現在我樂在其中,為什麼呢?肯定不是腦子壞了,因為我最近學會了一個超好用的格式化字符串的方法,那是相當的絲滑,所以我又迫不及待的來分享啦!
  • 程式設計師的術與道:術——編程基本功之字符串操作
    C語言字符串基本操作C語言中提供了大量豐富的字符串處理函數,用於輸入輸出的函數包含在stdio.h中而其他的字符串處理函數一般包含在string.h中。字符串基本操作字符串序列用於表示和存儲文本,python中字符串是不可變對象。
  • Python數據類型之字符串
    # 字符串是python中最常用的數據類型,我們可以使用引號來創建字符串,引號可以是單引號,雙引號或三引號,本質上單引號和雙引號以及三引號的作用是一樣的 # 字符串是一種不可變的序列類型,單個字符從左到右按照順序排列,同時修改某個位置的字符是不被允許的 #
  • 慢步學習二級python,字符串類型的操作:操作符,函數和方法
    繼續學習二級python考試的大綱內容:4.字符串類型的操作:字符串操作符,處理函數和處理方法學習字符串類型數據的操作是學習python的基礎。「love」字符串重複2次,再由+與前面「我愛你」連接。第3和第4個指令,也是在重複試驗*的作用。後面引入字符串變量a,a被賦值成字符串「God」,後續指令證實,字符串變量和字符串一樣都可以使用相應的操作符。倒數第2條指令,提示語法錯誤,字符串變量和字符串不能通過空格連接。
  • Go語言學習筆記之字符串一
    (str) fmt.Println( strings.HasPrefix(str, "Th")) //Contains 函數判斷字符串包含關係\ fmt.Println("\nContains函數判斷字符串包含關係:") str4 := "Ajian loves python and goland" fmt.Println(str4) fmt.Println(strings.Contains
  • Python中如何計算字符串的長度
    第七十二節:計算字符串長度在學習計算字符串的長度之前,需要先了解一個概念:字符編碼。字符編碼(Character encoding),即為字集碼,就是把字符集中的字符編碼為指定集合中某一對象,用來以字節為單位實現字符在計算機中的存儲,和便於通過通信網絡的傳遞字符。
  • Python - 超級好用的函數eval
    前言eval是Python的一個內置函數,這個函數的作用是,返回傳入字符串的表達式的結果。即變量賦值時,等號右邊的表示是寫成字符串的格式,返回值就是這個表達式的結果。命名空間python是用命名空間來記錄變量的軌跡的,命名空間是一個dictionary,鍵是變量名,值是變量值。在一個 Python 程序中的任何一個地方,都存在幾個可用的名字空間。每個函數都有著自已的名字空間,叫做局部名字空間,它記錄了函數的變量,包括函數的參數和局部定義的變 量。
  • Python中的變量與字符串數據類型
    假如我們給a賦值為0a = 1,那麼1就是整數類型的值,a就是整數類型的變量;如果a = 'hello word',那麼'hello word'就是字符串類型的值,a就是字符串類型的變量。1.1單索引讀取接下來我們通過索引來讀取中字符串中的姆,對應的下標是1.name[1]我們可以通過這種方式將字符串中的任意索引位置的字符串提取出來。
  • Oracle字符串替換小技巧,超實用
    資料庫中字符串的替換是比較常用的操作,Oracle已經為我們提供了幾個實用的函數來處理字符串的替換操作,常用的主要有replace、regexp_replace 和 translate三個函數,接下來我們來逐個看下。
  • SUBSTITUTE函數和REPLACE函數的用法比較
    如果用函數來解決,比較常用的替換函數有SUBSTITUTE 函數和REPLACE函數,在實際的工作中經常也會用到。有的朋友有的時候會經常出現疑惑,不清楚什麼時候該用哪個函數。其實,在某種意義上講,兩者都能實現替換,只是側重點不同。今日就兩個函數的用法給大家做詳細的講解。
  • 慢步學python,編程基礎,字符串類型例子及輸出
    想了解python的安裝及運行的可以看慢步之前寫的文章。今天繼續python編程基礎內容,字符串類型數據。python裡面主要的數據類型是數值類型和字符串類型。計算機可以進行運算的是數值,字符串不能進行數學運算,像你在閱讀的文字,可以理解為字符串的一種。
  • 分離中英文字符函數
    1、按字節截取字符 LEFTB(A2,4) 公式中4是要截取的字符包含的字節總數,在電腦中,1個漢字為2個字節。2、分離中英文字符函數公式 =LEFT(A2,LENB(A2)-LEN(A2) 公式主要意思是字符串包含的字節數與字符數的差值,就是這個字符串包含的雙字節字符(漢字)的個數。因為在電腦中,1個漢字佔2個字節,1個英文字母佔1個字節。他們的差值就是漢字的字節。
  • Python格式化輸出:%s和format()用法比較
    從python3.0開始起(python2.6同期發布),同時支持兩個版本的格式化,多出來的一個新版本就是利用format()函數,進行格式化輸出。2、為什麼要學習python3支持的新式格式化輸出呢?
  • python教程13課:python函數的詳細講解(一)
    python函數為什麼我們要定義函數?是為了將代碼模塊化提高代碼的重複使用率定義函數:函數代碼塊使用 def關鍵字開頭定義,後面跟上函數名稱和 ( ),後面再接上冒號任何傳入的參數都應該放到 括號裡面第二行開始函數裡面的內容使用縮進如果函數有返回值,咱們使用 return,如果沒有寫return,默認表示返回 None函數名必須以下劃線或者字母開頭,可以包含數字、字母、下劃線等組合
  • Python正則表達式:特殊符號和字符
    簡而言之,正則表達式(簡稱regex)是由一些字符和特殊符號組成的字符串,它描述了模式的重複或者表達多個字符。python通過標準庫中的re模塊來支持正則表達式。下圖是最常見的特殊符號和字符,也稱元字符,正是它給予正則表達式強大的功能和靈活性。
  • Python中簡單的函數,再不會就不好意思了
    多態傳入的參數可以接受任何數據類型比如,列表print(my_sum([1, 2], [3, 4]))# 輸出[1, 2, 3, 4]再比如,字符串,列表,字符串等等的操作稱為多態。函數嵌套函數嵌套就是函數中有函數,就叫嵌套函數了。
  • python入門教程06-01(python語法入門之字符編碼)
    解釋器執行文件的流程以python test.py為例,執行流程如下#階段1、啟動python解釋器,此時就相當於啟動了一個文本編輯器#階段2、python解釋器相當於文本編輯器,從硬碟上將test.py的內容讀入到內存中#階段3、python解釋器解釋執行剛剛讀入的內存的內容,開始識別python語法