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

后端 未结 1 1224
孤城傲影
孤城傲影 2021-02-04 05:54

In the reading of Python\'s Format Specification Mini-Language,

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]  
fill        ::=  

        
相关标签:
1条回答
  • 2021-02-04 06:34

    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.

    0 讨论(0)
提交回复
热议问题