2017-05-08 122 views
3

在Python的Format Specification Mini-Language的閱讀,python字符串格式中的冒號是什麼意思?

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" | "%" 

語法真的搞糊塗了。

例如,如果我想INT轉換爲二進制表示 我能做到這一點

"{0:b}".format(100) 
"{:b}".format(100) # but this is fine too, so what dose the 0 do? 

我知道b代表在規範type一部分,但我想不通的角色0:,他們在做什麼?

+0

請參閱https://pyformat.info/ – bigbounty

回答

3

你只是看語法爲format_spec,完整的語法指定higher up on the same page

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" 
field_name  ::= arg_name ("." attribute_name | "[" element_index "]")* 
arg_name   ::= [identifier | integer] 
attribute_name ::= identifier 
element_index  ::= integer | index_string 
index_string  ::= <any source character except "]"> + 
conversion  ::= "r" | "s" 
format_spec  ::= <described in the next section> 

replacement_field語法通知:format_spec前面。

field_name任選隨後通過轉換場,這是 感嘆號'!'之前,和一個format_spec,這是 一個冒號後面':'

field_name和/或conversion被指定,:標誌着前者的結束和format_spec的開始。

在您的例子,

>>> "{0:b}".format(100) 
'1100100' 

零指定可選field_name在這種情況下對應於傳遞的參數元組要格式化的項的索引;它是可選的,因此它可以被丟棄。

相關問題