str.format fails with JSON?

Chris Angelico rosuav at gmail.com
Tue Feb 21 10:28:10 EST 2017


On Wed, Feb 22, 2017 at 2:19 AM, Carlo Pires <carlopires at gmail.com> wrote:
> What I wanted was an output without errors, like:
>
> From {"value": 1}, value=1
>
> I think Python should ignore value not matching integers or identifiers. This will make str.format more robust and usable. It cannot be used if the text has JSON as string, for instance.

No, Python should most definitely not just ignore them. If the
behaviour is changed, it should be to catch the error in a more
friendly way, stating that a format directive was not a valid
identifier. To get the behaviour you want, double the braces that you
want to be literal, as I did in my example in my first reply.

Format strings are a mini-language. Like with any other, you need to
speak the grammar of that language. To include quotes and apostrophes
in a string literal, you need to either escape them with backslashes,
or use something else to surround the string; and since a backslash
can escape a quote, a backslash must itself be escaped. That's the
nature of the mini-language of string literals. When you layer in the
format codes, other characters gain meaning. If, instead, you layer in
printf formatting, braces won't be significant, but percent signs will
be. Etcetera. You can't escape this. (Pun intended.)

ChrisA



More information about the Python-list mailing list