在阅读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,在这种情况下,它对应于要在传递的参数元组中格式化的项的索引; 它是可选的,因此可以删除.
| 归档时间: |
|
| 查看次数: |
3846 次 |
| 最近记录: |