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

2021-07-02 07:13:19 字數 1446 閱讀 1861

1.填充

center(width[, fillchar]) ,

ljust(width[, fillchar]),

rjust(width[, fillchar]),

zfill(width),

expandtabs([tabsize])

* fillchar 引數指定了用以填充的字元,預設為空格

(1)string.center(width[, fillchar]) 返回乙個原字串居中,並使用空格填充至長度 width 的新字串

注意,當width-len(str)為奇數時,預設情況下左側填充的字元要比右側填充的字元要少。

另外,如果字串的長度比指定的位數要大時,該方法會返回原字串

例:>>> print 'abc'.center(12)

abc>>> print 'abc'.center(12, '*')

****abc*****

>>> print 'abc'.center(2,'*')

abc

(2)string.ljust(width[, fillchar]) 返回乙個原字串左對齊,並使用空格填充至長度 width 的新字串
>>> print 'abc'.ljust(12)

abc>>> print 'abc'.ljust(12, '*')

abc*********

>>> print 'abc'.ljust(2,'*')

abc

(3)string.ljust(width[, fillchar]) 返回乙個原字串右對齊,並使用空格填充至長度 width 的新字串
>>> print 'abc'.rjust(12)

abc>>> print 'abc'.rjust(12, '*')

*********abc

>>> print 'abc'.rjust(2,'*')

abc

(4)string.zfill(width) 返回長度為 width 的字串,原字串 string 右對齊,前面填充0
>>> print 'abc'.zfill(12)

000000000abc

>>> print 'abc'.zfill(2)

abc

(5)string.expandtabs([tabsize])的tabsize 引數預設為8。它的功能是把字串中的製表符(tab)轉換為適當數量的空格。
>>> print len('abc  ')

5>>> print len('abc '.expandtabs())

5>>> print 'abc '.expandtabs().replace(' ','*')

abc**

問題:為什麼製表符只有2個字元?說好的8個字元呢?難道是系統的原因?

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

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

Python字串方法詳細介紹3 變形

3.變形 lower upper capitalize swapcase title 這幾個方法比較簡單,它們不需要輸入引數,返回相應的結果 1 lower 將原字串的字元全部轉成小寫字母,若有數字或其他字元就原樣輸出 print abc1 lower abc1 2 upper 與lower 相反,...

Python字串基本方法介紹

upper 轉大寫 lower 轉小寫 isalnum 是否全是字母和數字,並至少有乙個字元 isdigit 是否全是數字,並至少有乙個字元 isalpha 是否全是字母,並至少有乙個字元 isupper 是否全是大寫,當全是大寫和數字一起時候,也判斷為true islower 是否全是小寫,當全是...