Search code examples
pythonstring-formatting

What is the meaning of a colon in string formatting?


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

the grammar really confused me.

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

"{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?


Solution

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

    In the replacement_field syntax notice the : preceding the format_spec.

    The field_name is optionally followed by a conversion field, which is preceded by an exclamation point '!', and a format_spec, which is preceded by a colon ':'

    When the field_name and/or conversion are specified, : marks the end of former and the start of the 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; it is optional so it can be dropped.