Why is Python interpreting this string as a dictionary when formatting?
我在使用一个类似于Python字典的字符串时遇到了问题。
我想生成以下字符串:
1 | '{"one":{}}'.format(1) |
解释器抛出一个键错误:
1 2 3 4 | >>> a = '{"one":{}}'.format(1) Traceback (most recent call last): File"<stdin>", line 1, in <module> KeyError: '"one"' |
我理解,这个问题可能是围绕着字符串包含
我知道百分比格式,但我想找到一个不涉及放弃
如文件所述:
The
field_name itself begins with anarg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.
(emphasis mine)
这就是为什么您得到
作为一种解决方案,只需避开外部大括号:
1 2 | >>> '{{"one":{}}}'.format(1) '{"one":1}' |
如果您决定将来使用
1 2 | >>> f'{{"one": {1}}}' '{"one": 1}' |
您需要双大括号
1 | a= '{{"one":{}}}'.format(1) |
来自DOC:
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}} .
如果不转义大括号,
1 2 | b = '{"one"} foo'.format(**{'"one"':1}) print(b) # 1 foo |
大括号可以使用双大括号转义,使用:
1 | '{{"one":{}}}'.format(1) |