为什么 Python 在格式化时将此字符串解释为字典?
Why is Python interpreting this string as a dictionary when formatting?
我在使用 format
和看起来像 Python 字典的字符串时遇到问题。
我想生成以下字符串:{"one":1}
如果我尝试这样做:
'{"one":{}}'.format(1)
解释器抛出 KeyError:
>>> a = '{"one":{}}'.format(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '"one"'
我知道这个问题可能是因为字符串包含 {
,这可能会与 format
的 {}
混淆。为什么会发生这种情况,如何解决?
我知道百分比格式,但我想找到一个不涉及放弃的解决方案 format()
。
'{"one": {}}'
的格式是 using an identifier as the field_name
,本质上将尝试查找已提供给 .format
且名称为 '"one"'
的关键字参数。
如文档所述:
The field_name
itself begins with an arg_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.
(强调我的)
这就是为什么您得到 KeyError
异常;它试图在提供给 format
的关键字参数映射中寻找键。 (在这种情况下,它是空的,因此是错误的)。
作为解决方案,只需转义外花括号即可:
>>> '{{"one":{}}}'.format(1)
'{"one":1}'
如果您决定将来使用 f
-字符串,同样的补救措施适用:
>>> f'{{"one": {1}}}'
'{"one": 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 }}
.
如果不转义大括号,str.format()
将查找键 '"one"'
的值来格式化字符串。例如:
b = '{"one"} foo'.format(**{'"one"':1})
print(b) # 1 foo
大括号可以使用双大括号进行转义,使用:
'{{"one":{}}}'.format(1)
我在使用 format
和看起来像 Python 字典的字符串时遇到问题。
我想生成以下字符串:{"one":1}
如果我尝试这样做:
'{"one":{}}'.format(1)
解释器抛出 KeyError:
>>> a = '{"one":{}}'.format(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '"one"'
我知道这个问题可能是因为字符串包含 {
,这可能会与 format
的 {}
混淆。为什么会发生这种情况,如何解决?
我知道百分比格式,但我想找到一个不涉及放弃的解决方案 format()
。
'{"one": {}}'
的格式是 using an identifier as the field_name
,本质上将尝试查找已提供给 .format
且名称为 '"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.
(强调我的)
这就是为什么您得到 KeyError
异常;它试图在提供给 format
的关键字参数映射中寻找键。 (在这种情况下,它是空的,因此是错误的)。
作为解决方案,只需转义外花括号即可:
>>> '{{"one":{}}}'.format(1)
'{"one":1}'
如果您决定将来使用 f
-字符串,同样的补救措施适用:
>>> f'{{"one": {1}}}'
'{"one": 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}}
.
如果不转义大括号,str.format()
将查找键 '"one"'
的值来格式化字符串。例如:
b = '{"one"} foo'.format(**{'"one"':1})
print(b) # 1 foo
大括号可以使用双大括号进行转义,使用:
'{{"one":{}}}'.format(1)