Python3,字符串函數整理

rsplit從後往前分割

>>> "banana".split("n",1)
['ba', 'ana']
>>> "banana".rsplit("n",1)
['bana', 'a']

capitalize首字母大寫

>>> 'GrEat'.capitalize()
'Great'

casefold:lower() 方法只對ASCII編碼,也就是‘A-Z’有效,對於其他語言(非漢語或英文)中把大寫轉換爲小寫的情況只能用 casefold() 方法。

>>> 'GreaTEr'.casefold()
'greater'

非字母后的第一個字母將轉換爲大寫字母

>>> "This is a 3g3g".title()
'This Is A 3G3G'

center,ljust,rjust

>>> "great".center(20, '*')
'*******great********'
>>> "great".ljust(20, '*')
'great***************'
>>> "great".rjust(20, '*')
'***************great'

count計數

"This is a dog".count("s")
2

expandtabs製表符轉換爲空格

>>> '\t'.expandtabs()
'        '
>>> '\t\t'.expandtabs()
'                '

partition、rpartition分割成三個元素並放入到元組中

>>> "This is a pig".partition("is")
('Th', 'is', ' is a pig')
>>> "This is a pig".rpartition("is")
('This ', 'is', ' a pig')

index,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常。

>>> 'This is a dog'.index("i", 4, 10)
5

swapcase大小寫轉換

>>> "GrEat".swapcase()
'gReAT'

translate,先做翻譯表

>>> intab = "aeiou"
>>> outtab = "12345"
>>> trantab = str.maketrans(intab, outtab)   # 製作翻譯表
>>> str = "this is string example....wow!!!"
>>> print (str.translate(trantab))
th3s 3s str3ng 2x1mpl2....w4w!!!

startswith。endswith

>>> "greater".startswith("great")
True
>>> "greater".endswith("er")
True

format_map,與format類似

>>> People = {"name": "john", "age": 33}
>>> print("My name is {name},iam{age} old".format_map(People))
My name is john,iam33 old

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章