Python的格式不适用于包含JSON

时间:2017-02-20 13:03:59

标签: python python-2.7 python-3.x

此代码:

'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表现得那样?我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

如果要在输出中包含实际括号Number.append(int(j)) ,则需要执行以下操作:

{}

格式将括号'{{"value": 1}}, {}'.format(0) 中的所有内容视为参数。空括号表示位置值,其他所有内容都是treatet作为关键字参数。