python的字符串格式中冒号的含义是什么?

Ziu*_*Ziu 13 python

在阅读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" | "%"   
Run Code Online (Sandbox Code Playgroud)

语法真让我困惑.

例如,如果我想将int转换为二进制表示,我可以这样做

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

我知道,b代表了type在规范的一部分,但我想不通的角色0:,他们在干什么?

Mos*_*oye 11

你只是查看语法,在同一页面上format_spec指定了更高的完整语法:

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>
Run Code Online (Sandbox Code Playgroud)

replacement_field语法上注意:前面的format_spec.

field_name任选地随后通过转换场,这是由前面带有感叹号'!',并且format_spec,这是一个冒号之前':'

field_name和/或被conversion指定时,:标记前者的结束和开始format_spec.

在你的例子中,

>>> "{0:b}".format(100)
'1100100' 
Run Code Online (Sandbox Code Playgroud)

zero指定可选项field_name,在这种情况下,它对应于要在传递的参数元组中格式化的项的索引; 它是可选的,因此可以删除.