Why does the symbol '{' remain when f"\{10}" is evaluated in Python 3.6?

481 Views Asked by At

The f-string is one of the new features in Python 3.6.

But when I try this:

>>> f"\{10}"
'\\{10'

I can't figure out why the left curly brace '{' remains in the result. I supposed that the result should be same with the str.format:

>>> "\{}".format(10)
'\\10'

In PEP-0498 it doesn't answer this explicitly. So what causes that the left curly brace '{' to remain in the result and what causes this difference between f-string and str.format()?

1

There are 1 best solutions below

0
On BEST ANSWER

This is a bug. An approach that currently works is to use the Unicode literal \u005c for \ instead:

>>> f'\u005c{10}'
'\\10'

or, with a similar effect, using a raw f-string:

>>> rf'\{10}'
'\\10'

By using '\' it seems that the two weird things happen at the same time:

  • The next character ('{' here) was escaped, leaving it in the resulting string.
  • The formatted string is also evaluated, which is odd and not expected

Case in point:

>>> f'\{2+3}'
'\\{5'
>>> a = 20
>>> f'\{a+30}'
'\\{50'

Either way, I'll be filling out a bug report soon (since I see you haven't already) and update when I get a reply.

Update: Created Issue 29104 -- Left bracket remains in format string result when '\' preceeds it, if you're interested take a look at the conversation there.

Update 2: Issue resolved with PR 490.