Python標準庫:內建函數format(value[, format_spec]),pythonformat_spec
本函數把值value按format_spec的格式來格式化,然而函數解釋format_spec是根據value的類型來決定的,不同的類型有不同的格式化解釋。當參數format_spec為空白時,本函數等同於函數str(value)的方式。
其實本函數調用時,是把format(value, format_spec)的方式轉換為type(value).__format__(format_spec)方式來調用,因此在value類型裡就尋找方法__format__(),如果找不到此方法,就會返回異常TypeError。
其中format_spec的編寫方式如下形式:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
fill是表示可以填寫任何字元。
align是對齊,<是靠左對齊, >是靠右對齊,^是置中對齊。
sign是符號, +表示正號, -表示負號。
width是數字寬度,表示總共輸出多少位元字。
precision是小數保留位元。
type是輸出數字值是的表示方式,比如b是二進位表示;比如E是指數表示;比如X是十六進位表示。
例子:
#format()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'))
結果輸出如下:
2918
500
0000003.14
03.14
3.141590E+00
test
test
test
蔡軍生 QQ:9073204 深圳