str.format fails with JSON?
carlopires at gmail.com
carlopires at gmail.com
Tue Feb 21 09:23:29 EST 2017
Hi,
When I run this piece of code:
'From {"value": 1}, value={value}'.format(value=1)
Python complains about the missing "value" parameter (2.7.12 and 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"
But according to the format string syntax (https://docs.python.org/2/library/string.html):
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>
The replacement_field, which in this case, is composed by an identifier, shouldn't have quotation marks. Here is the lexical definition for an identifier (according to the documentation):
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
So according to the specification, {value} should be recognized as a valid format string identifier and {"value"} should be ignored.
Python seems to not follow the specification in the documentation. Anything inside the keys is accepted as identifier.
More information about the Python-list
mailing list