简体   繁体   English

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

[英]what is the meaning of colon in python's string format?

In the reading of Python's 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" | "%"   

the grammar really confused me. 语法真让我困惑。

For example, if I want to convert int to binary representation I can do this 例如,如果我想将int转换为二进制表示,我可以这样做

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

I know that b represent the type part in the specification, but I can't figure out the role for 0 and : , what are they doing? 我知道b代表规范中的type部分,但我无法弄清00的作用:它们在做什么?

You are only looking at the grammar for the format_spec , the full grammar is specified higher up on the same page : 您只查看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>

In the replacement_field syntax notice the : preceding the format_spec . replacement_field语法中,请注意: format_spec之前的:

The field_name is optionally followed by a conversion field, which is preceded by an exclamation point '!' 所述field_name任选地随后通过转换场,这是由前面带有感叹号'!' , and a format_spec , which is preceded by a colon ':' format_spec ,前面有冒号':'

When the field_name and/or conversion are specified, : marks the end of former and the start of the format_spec . 指定field_name和/或conversion:标记前者的结束和format_spec的开始。

In your example, 在你的例子中,

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

zero specifies the optional field_name which in this case corresponds to the index of the item to be formatted in the passed parameter tuple; zero指定可选的field_name ,在这种情况下,对应于要在传递的参数元组中格式化的项的索引; it is optional so it can be dropped. 它是可选的,因此可以删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM