嗨,我正在读取一个源,它有一行:
fn = 'total-listmix-{}-{}.xml'.format(opt.os, opt.compiler)
exept Exception as e:
raise Exception('error merging coverage: {}'.format(e))
我认为{}
是指dict
,但我不明白这里的dict
是什么?dict
是否取自format
?
{}
是一个替换字段,而不是dict
。Python文档:中提到了这一点
格式化字符串包含由大括号
{}
包围的"替换字段"。任何不包含在大括号中的内容都被视为文字文本,它被原封不动地复制到输出中。如果需要在文本中包含大括号字符,可以通过加倍{{
和}}
来转义。
一个简单的例子是:
name = "Tom"
print("Hello, {}".format(name)) # prints "Hello, Tom"
以下是Python文档中的更多示例:
"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'.
这就是替换字段的语法:
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>