What is the meaning of colon in python string format?

When reading the Python format specification mini-language ,

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

grammar really confused me.

For example, if I want to convert int to binary representation, I can do it

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

I know what bthe part typein the specification represents , but I cannot understand the role for 0and :what do they do?

+4
source share
1 answer

You are only looking at the grammar for format_spec, the full grammar is listed above 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>

In the syntax, replacement_fieldpay attention to the :foregoing format_spec.

field_name , , '!', a format_spec, ':'

field_name / conversion, : format_spec.

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

zero field_name, , ; , .

+3

Source: https://habr.com/ru/post/1676656/


All Articles