標籤:space 大小 並且 strip 置中 元素 lse 刪除字串 tran
capitalize() 把字串的第一個字元改為大寫
str1 = 'xiaoxie'
str1.capitalize()
→Xiaoxie
casefold() 把整個字串的所有字元改為小寫
>>> str1 = 'ASSDFAWEadfaAjjIlOOOMMkl'
>>> str1.casefold()
'assdfaweadfaajjilooommkl'
center(width) 將字串置中,並使用空格 填充至長度width的新字串
>>> str1 = 'asdfaef'
>>> str1.center(15)
' asdfaef '
count(sub,[,start[,end]]) 返回sub在字串裡邊出現的次數,start和end參數表示範圍
endswith(sub[,start[,end]]) 檢查字串是否以sub字串結束,如果是返回True,否則返回False
>>> str1
'asdfaef'
>>> str1.endswith('ef')
True
expandtabs([tabsize=8]) 把字串中的tab符號(\t)轉換為空白格,如果不指定參數,預設的空格數是tabsize=8
>>> str1 = 'I\tlova\tU'
>>> str1.expandtabs()
'I lova U'
find(sub[,start[,end]]) 檢查sub是否包含在字串中,如果有則返回索引值所在的位置,否則返回-1
rfind(sub[,start[,end]])從右邊開始找
>>> str1
'I\tlova\tU'
>>> str1.find('i')
-1
>>> str1.find('I')
0
index(sub[,start[,end]]) 跟find方法一樣,不過如果sub不在string中會產生一個異常
rindex(sub[,start[,end]])
isalnum() 如果字串至少有一個字元並且所有字元都是字母或數字則返回True
isalpha() 如果字串至少有一個字元並且所有字元都是字母則返回True
isdecima() 如果字串只包含十進位數字則返回True
isdigit() 如果字串只包含數字則返回True
islower() 如果這些字元都是小寫則返回True
isnumeric() 如果字串中只包含數字字元則返回True
isspace() 如果字串中只包含空格,則返回True
istitle() 如果字串中所有單詞的首字母為大寫,其他均小寫則返回True
isupper() 如果所有字元都是大寫則返回True
join(sub) 以字串作為分隔字元,插入到sub中所有的字元之間
>>> str1
'IloveU'
>>> str1.join('12345')
'1IloveU2IloveU3IloveU4IloveU5'
ljust(width) 返回一個靠左對齊的字串,並使用空格填充
lower() 轉換字串中所有大寫字元為小寫
lstrip() 去掉字串左邊的所有空格
rstrip()
>>> str1 = ' Ilove U'
>>> str1.lstrip()
'Ilove U'
parttition(sub) 找到子字串sub,把字串分成一個3元組
rparttition(sub)
>>> str1 = 'IloveU'
>>> str1.partition('ve')
('Ilo', 've', 'U')
replace(old,new[,count]) 把字串中的old子字串替換成new子字串,如果count指定,則替換不超過count次
>>> str1
'IloveU'
>>> str1.replace('Ilove','I donot now')
'I donot nowU'
split(sep=none,maxsplit=-1)不帶參數預設是以空格為分隔字元
>>> str1 = 'I love U likeme'
>>> str1.split()
['I', 'love', 'U', 'likeme']
>>> str1.split('l')
['I ', 'ove U ', 'ikeme']
splitilines() 按照'/n'分隔,返回一個包含各行作為元素的列表
strip([chars]) 刪除字串前邊和後邊所有的空格
swapcase() 翻轉字串中的大小寫
translate() 根據table的規則(可以由str.maketrans('a','b')定製)轉換字串中的字元
>>> str1 = 'abcfasdfkkeaaaff'
>>> str1.translate(str.maketrans('a','2'))
'2bcf2sdfkke222ff'
upper() 轉換字串中的所有小寫字元為大寫
zfill(width) 返回長度為width的字串,原字串靠右對齊,前邊用0填充
Python內建字串