自python2.6開始,新增了一種格式化字串的函式str.format(),它通過{}和:來代替%
位置方法格式化
通過關鍵字引數
通過物件屬性
>>> class website:
def __init__(self,name,type):
self.name,self.type = name,type
def __str__(self):
return 'website name: , website type: '.format(self=self)
>>> print str(website('pythontab.com', 'python'))
website name: pythontab.com, website type: python
>>> print website('pythontab.com', 'python')
website name: pythontab.com, website type: python
通過下標
有了這些便捷的「對映」方式,我們就有了偷懶利器。基本的python知識告訴我們,list和tuple可以通過「打散」成普通引數給函式,而dict可以打散成關鍵字引數給函式(通過和*)。所以可以輕鬆的傳個list/tuple/dict給format函式, 非常靈活。
格式限定符
它有著豐富的的「格式限定符」(語法是{}中帶:號),比如:
填充與對齊
填充常跟對齊一起使用
^、<、>分別是居中、左對齊、右對齊,後面帶寬度
:號後面帶填充的字元,只能是乙個字元,不指定的話預設是用空格填充
>>> ''.format(2016)
' 2016'
>>> ''.format(2016)
'######2016'
>>> ''.format(2016)
'0000002016'
數字精度與型別f
精度常跟型別f一起使用
>>> ''.format(2016.0721)
'2016.07'
其中.2表示長度為2的精度,f表示float型別。
其他型別
主要就是進製了,b、d、o、x分別是二進位制、十進位制、八進位制、十六進製制。
>>> ''.format(2016)
'11111100000'
>>> ''.format(2016)
'2016'
>>> ''.format(2016)
'3740'
>>> ''.format(2016)
'7e0'
用,號還能用來做金額的千位分隔符。
>>> ''.format(20160721)
'20,160,721'
format的功能太強大了, 還有很多功能, 大家可以去嘗試一下。
python筆記 字串格式化函式format
自python2.6開始,新增了一種格式化字串的函式str.format 通過 和 來代替 通過位置 in 1 format cqk 20 out 1 cqk,20 in 2 format cqk 20 out 2 cqk,20 in 3 format cqk 20 out 3 20,cqk,20 ...
字串格式化函式
trim 函式 預設功能為去除字串首尾處的空格 或其它字元 返回乙個人新的字串 str hello world echo str的長度為 strlen str nstr trim str echo 新陣列 nstr的長度為 strlen nstr 去除左邊的空格用ltrim 函式 lstr ltri...
WSPRINTF格式化字串函式
win32 api中乙個很常用的函式wsprintf,這是乙個字串格式化函式,可以將數值按指定格式翻譯成字串,類似於c語言中的printf函式,它的原型是這樣的 int wsprintf lptstr lpout,輸出緩衝區位址 lpctstr lpfmt,格式化串位址 變數列表 變數列表的數目由格...