Search code examples
pythontestingautomated-testscode-coveragecoverage.py

what does {} and format do in this command python?


Hi i am reading a source and it has a line:

fn = 'total-listmix-{}-{}.xml'.format(opt.os, opt.compiler)
exept Exception as e:
    raise Exception('error merging coverage: {}'.format(e))

I think the {} mean a dict but i do not understand what dict here ? Is is a dict took from format ?


Solution

  • The {} is a replacement field, not a dict. This is mentioned in the Python Documentation:

    Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

    One simple example is:

    name = "Tom"
    print("Hello, {}".format(name)) # prints "Hello, Tom"
    

    Here are a few more examples from the Python Documentation:

    "First, thou shalt count to {0}"  # References first positional argument
    "Bring me a {}"                   # Implicitly references the first positional argument
    "From {} to {}"                   # Same as "From {0} to {1}"
    "My quest is {name}"              # References keyword argument 'name'
    "Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
    "Units destroyed: {players[0]}"   # First element of keyword argument 'players'.
    

    And this is the grammar of the replacement field:

    replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
    field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
    arg_name          ::=  [identifier | digit+]
    attribute_name    ::=  identifier
    element_index     ::=  digit+ | index_string
    index_string      ::=  <any source character except "]"> +
    conversion        ::=  "r" | "s" | "a"
    format_spec       ::=  <described in the next section>