字符串操作一
阿新 • • 發佈:2018-01-14
rip strip() har split center 替換 大小 char 轉變 S.strip 函數:
可以將字符串的左右空格\t等空白內容去除,該函數可以將字符串的左右兩邊
的空格、 \t等空白內容或指定字符串去除,並返回處理後的結果,但原字符串
並未被改變。
不帶參數的strip()函數,表示把S中前後所有的空白字符全部去掉,包括
’ \n’ , ‘\t’ , ‘\r’ , ’ ’ 等不可見字符串,可以理解為把S前後空白字
符串替換為None;帶參數的strip()函數表示將S前後指定字符串chars去掉。
用法:S.strip([chars])
s = "* boy* boy *boy ***" s_s = s.strip(‘*‘) print s_s boy* boy *boy
lstrip()
可以將字符串的左邊空格\t等空白內容去除
s = ‘* My is good!*‘
print s.lstrip(‘*‘)
== My is good!*
rstrip()函數
可以將字符串的右邊空格\t等空白內容去除
s = ‘* My is good!*‘
print s.rstrip(‘*‘)
==* My is good!
lower()函數
將字符串轉變為小寫
print ‘S‘.lower()
upper()函數
將字符串轉變為小寫
print‘s‘.upper()
swapcase()函數
將字符串的大小寫互換
print ‘s‘.swapcase()
capitalize() 函數
將字符串的首個字母轉換為大寫
print‘acb‘.capitalize()
Acb
capwords()函數
把字符串中的每個單詞首字符轉換為大寫
string.capwords(s)
‘***my Very Good‘
String.capwords(S)
#這是模塊中的方法。它把S用split()函數分開,然後用capitalize()把首字母變成大寫,最後用join()合並到一起
string.capwords(s)
‘***my Very Good‘
S.title() 函數
將字符串的每個單詞首字母大寫
print ‘My good‘.title()
My Good
S.ljust()函數
S.ljust(width,[fillchar])
#輸出width個字符,S左對齊,不足部分用fillchar填充,默認的為空格。
print s.ljust(10,‘*‘)
123good***
代碼示例2:
默認不寫第二個參數,則使用
空格填充
s = ‘123good‘
print s.ljust(11)
123good
S.rjust()函數
S.rjust(width,[fillchar]) #右對齊
代碼示例:
s = ‘123good‘
#執行結果:
print s.rjust(15,‘*‘)
********123good
S.center()
S.center(width, [fillchar]) #中間對齊代碼示例:
執行結果:
print s.center(15,‘*‘)
****123good***
S.zifll()填充
S.zfill(width)
#把S變成width長,並在右對齊,不足部分用0補足
代碼示例4:
print s.zfill(20)
執行結果:
print s.zfill(20)
0000000000000123good
字符串操作一