Python 字串中常見的一些方法

2022-08-17 06:36:09 字數 2230 閱讀 2370

str.capitalize()

將字串的第乙個字母變成大寫,其他字母變小寫。

str = "

this is string example!!!

"print(str.capitalize())

結果:

this is string example!!!

str.title()

所有單詞的首個字母轉化為大寫,其餘字母均為小寫。

str = "

this is string example!!!

"print(str.title())

結果:

this is string example!!!

str.upper()

將字串中的小寫字母轉為大寫字母。

str = "

this is string example!!!

"print(str.upper())

結果:

this is string example!!!

str.lower()

轉換字串中所有大寫字元為小寫。

str = "

this is string example!!!

"print(str.lower())

結果:

this is string example!!!

str.swapcase()

對字串的大小寫字母進行轉換。

str = "

this is string example!!!

"print(str.swapcase())

結果:

this is string example!!!

str.center(width[,fillchar])

返回乙個指定的寬度 width 居中的字串,fillchar 為填充的字元,預設為空格。

若指定的 width 小於字串寬度則直接返回字串。

width -- 字串的總寬度。

fillchar -- 填充字元。預設為空格

str = "

[櫻]"

print (str.center(40, '

*'))

結果:

******************[櫻]*******************

str.ljust(width[,fillchar])

返回乙個指定的寬度 width 左對齊的字串,fillchar 為填充的字元,預設為空格。

若指定的 width 小於字串寬度則直接返回字串。

width -- 字串的總寬度。

fillchar -- 填充字元。

預設為空格

str = "

[櫻]"

print (str.ljust(40, '

*'))

結果:

[櫻]*************************************

str.rjust(width[,fillchar])

返回乙個指定的寬度 width 右對齊的字串,fillchar 為填充的字元,預設為空格。

若指定的 width 小於字串寬度則直接返回字串。

width -- 字串的總寬度。

fillchar -- 填充字元。預設為空格

str = "

[櫻]"

print (str.rjust(40, '

*'))

結果:
*************************************[櫻]

str.zfill(width)

返回乙個指定的長度 width 右對齊的字串,前面填充0。

若指定的 width 小於字串長度則直接返回字串。

width -- 字串的長度。

str = "

[櫻]"

print (str.zfill(40))

結果:

0000000000000000000000000000000000000[櫻]

python中常見的字串操作

如有字串mystr hello world and bjsxt yunshuxueyuan sxt beijing 以下是常見的操作 1 find 檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則返回 1 mystr.find str,start 0,end len mystr ...

python的一些字串操作

寫這個部落格主要是為了記錄下我學習python的過程以及知識 也可能會有其他程式語言 雖說都是一些比較基礎的東西,但有的確實很快就會遺忘,記錄下來就來這裡檢視,會方便很多。我知道,現在才起步,已經比別人晚了許多,希望自己能堅持下去,不至於落後別人太多,2019,加油!好了,言歸正傳,還是先回顧一下之...

python字串的一些方法

最重要的方法 find startwith format is類方法 strip split print 1,20 a 123 b abc c 44 d join a,b,c 字串拼接方法 print 2,d st hello kitty print 2,st.count 1 print 3,st....