新聞中心
格式化在程序開(kāi)發(fā)中非常常見(jiàn),大家肯定不陌生,Python中也存在多重格式化方式,F(xiàn)ORMAT函數(shù)就是其中一種。

函數(shù)原型
format(value[, format_spec])
參數(shù)意義
value: 需要被格式化的字符串
format_spec: 格式化的格式
函數(shù)定義與用法
本函數(shù)把值value按format_spec的格式來(lái)格式化,然而函數(shù)解釋format_spec是根據(jù)value的類(lèi)型來(lái)決定的,不同的類(lèi)型有不同的格式化解釋。當(dāng)參數(shù)format_spec為空時(shí),本函數(shù)等同于函數(shù)str(value)的方式。
format () 函數(shù)可以接受不限個(gè)參數(shù),位置可以不按順序。
其實(shí)本函數(shù)調(diào)用時(shí),是把format(value, format_spec)的方式轉(zhuǎn)換為type(value).__format__(format_spec)方式來(lái)調(diào)用,因此在value類(lèi)型里就查找方法__format__(),如果找不到此方法,就會(huì)返回異常TypeError。
其中format_spec的編寫(xiě)方式如下形式:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::=align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= integerprecision ::= integertype ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" fill是表示可以填寫(xiě)任何字符。 align是對(duì)齊方式,<是左對(duì)齊, >是右對(duì)齊,^是居中對(duì)齊。 sign是符號(hào), +表示正號(hào), -表示負(fù)號(hào)。w idth是數(shù)字寬度,表示總共輸出多少位數(shù)字。 precision是小數(shù)保留位數(shù)。
兼容性
Python3.x
Python2.6及以上版本
注意事項(xiàng)
format是是python2.6新增的一個(gè)格式化字符串的方法,相對(duì)于老版的%格式方法,它有很多優(yōu)點(diǎn)。
1.不需要理會(huì)數(shù)據(jù)類(lèi)型的問(wèn)題,在%方法中%s只能替代字符串類(lèi)型
2.單個(gè)參數(shù)可以多次輸出,參數(shù)順序可以不相同
3.填充方式十分靈活,對(duì)齊方式十分強(qiáng)大
4.官方推薦用的方式,%方式將會(huì)在后面的版本被淘汰
代碼實(shí)例
print(format(2918))
print(format(0x500, 'X'))
print(format(3.14, '0=10'))
print(format(3.14159, '05.3'))
print(format(3.14159, 'E'))
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
輸出結(jié)果
2918 500 0000003.14 03.14 3.141590E+00 test test test
標(biāo)題名稱(chēng):創(chuàng)新互聯(lián)Python教程:Python中format函數(shù)字符串格式化入門(mén)
網(wǎng)頁(yè)URL:http://m.5511xx.com/article/coghgdc.html


咨詢(xún)
建站咨詢(xún)
