1. 程式人生 > >python中字串(str)的常用處理方法

python中字串(str)的常用處理方法

生成字串變數str='python String function'

字串長度獲取:len(str)
例:print '%s length=%d' % (str,len(str))

一、字母處理
全部大寫:str.upper()
全部小寫:str.lower()
大小寫互換:str.swapcase()
首字母大寫,其餘小寫:str.capitalize()
首字母大寫:str.title()
print '%s lower=%s' % (str,str.lower())
print '%s upper=%s' % (str,str.upper())
print '%s swapcase=%s' % (str,str.swapcase())
print '%s capitalize=%s' % (str,str.capitalize())
print '%s title=%s' % (str,str.title())
二、格式化相關
獲取固定長度,右對齊,左邊不夠用空格補齊:str.ljust(width)
獲取固定長度,左對齊,右邊不夠用空格補齊:str.ljust(width)
獲取固定長度,中間對齊,兩邊不夠用空格補齊:str.ljust(width)
獲取固定長度,右對齊,左邊不足用0補齊
print '%s ljust=%s' % (str,str.ljust(20))
print '%s rjust=%s' % (str,str.rjust(20))
print '%s center=%s' % (str,str.center(20))
print '%s zfill=%s' % (str,str.zfill(20))