Python字串基本方法介紹

2021-07-23 16:37:22 字數 1312 閱讀 4918

upper() #轉大寫

lower() #轉小寫

isalnum() #是否全是字母和數字,並至少有乙個字元

isdigit() #是否全是數字,並至少有乙個字元

isalpha() #是否全是字母,並至少有乙個字元

isupper() #是否全是大寫,當全是大寫和數字一起時候,也判斷為true

islower() #是否全是小寫,當全是小寫和數字一起時候,也判斷為true

isspace() #是否全是空白字元,並至少有乙個字元

istitle() #所有單詞字首都是大寫,標題

startswith(』s』) #判斷字串以』s』開頭

endswith(』s』) #判讀字串以』s』結尾

str.find(』s』) #查詢字串,沒有則返回-1,有則返回查到到第乙個匹配的索引

rfind(』s』) #同find,區別是返回的索引是最後一次匹配的 (類似其他語言的lastindexof)

index(』s』) #同find,區別是沒有找到就報錯

rindex(』s』) #同rfind,區別是沒有找到就報錯

count(』s』) #字串中匹配的次數

replace(『old』,』new』) #替換匹配到的所有字串(類似其他語言的replaceall)

replace(『old』,』new』,count)#替換count個匹配到的字串,如果count為1,匹配多個的情況下只替換第乙個

strip(』s』) #刪除字串首尾匹配的字元

lstrip(』s』) #刪除字串首匹配的字元

rstrip(』s』) #刪除字串尾匹配的字元

expandtabs() #把製表符轉為空格

encode(『charset』)#將unicode編碼重新編碼為charset字符集格式的字串,如charset為utf-8時,返回utf-8格式的字串

decode(『charset』)#將charset編碼重新解碼為unicode字符集格式的字串,如字串原為utf-8編碼並且charset為utf-8,返回unicode格式的字串

join(』s』) #將字串中的字元用』s』拼接

split(』s』) #將字串中的字元用』s』拆分

split(』s』,count) #將字串中的字元用』s』拆分,只拆分匹配到的第count個』s』

partition(』s』)#同split,區別是保留』s』在返回的列表中

python中,string是乙個特殊的list,凡是list有的方法,string也是有的

python字串的介紹

建立字串 str1 hello str2 hello 字串的運算 字串的拼接 1.使用 號 str3 str1 str2 2 使用 號 注意 在輸出的時候使用,在逗號的位置會產生乙個空格 3.使用 號 s字串 4.使用join函式來進行拼接 str1.join 序列 功能 以指定的字串對序列中的元素...

Python字串方法詳細介紹1 填充

1.填充 center width fillchar ljust width fillchar rjust width fillchar zfill width expandtabs tabsize fillchar 引數指定了用以填充的字元,預設為空格 1 string.center width ...

Python字串方法詳細介紹2 刪除

2.刪減 strip chars lstrip chars rstrip chars 1 strip chars strip 函式族用以去除字串兩端的空白符,保留中間的空白符 空白符由string.whitespace常量定義 print abc d strip replace abc d x li...