gpt4 book ai didi

Python 的格式不适用于包含 JSON 的文本

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:42 25 4
gpt4 key购买 nike

这段代码:

'From {"value": 1}, value={value}'.format(value=1)

失败如下(Python 2.7.12 和 Python 3.6.x):

Traceback (most recent call last):
File "test_format.py", line 1, in <module>
'From {"value": 1}, value={value}'.format(value=1)
KeyError: '"value"

Python 解释器提示 "value" 没有在 format 方法的参数中传递。

但是根据format string syntax :

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>

在本例中,replacement_field标识符 组成,不应有引号。以下是标识符的词法定义:

identifier ::=  (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"

因此根据规范,{value} 应该被识别为有效的格式字符串标识符,{"value"} 应该被忽略。

Python 似乎不遵循文档中的规范。键内的任何内容都被接受为标识符

为什么 python 会这样?我在这里缺少什么?

最佳答案

如果您想在输出中包含实际的括号 {},您需要这样做:

'{{"value": 1}}, {}'.format(0)

Format 将方括号 {} 中的所有内容都视为参数。空括号表示位置值,其他所有内容都被视为关键字参数。

关于Python 的格式不适用于包含 JSON 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com