Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()?

like image 931
lazzzis Avatar asked Dec 26 '16 10:12

lazzzis


People also ask

Does Python 3.6 have F-strings?

As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!

What was introduced in Python 3.6 that changed string formatting?

Python 3.6 introduced a new way to format strings: f-Strings. It is faster than other string formatting methods in Python, and they allow us to evaluate Python expressions inside a string.

What does %s indicate in Python?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.

What is %d and %f in Python?

For example, "print %d" % (3.78) # This would output 3 num1 = 5 num2 = 10 "%d + %d is equal to %d" % (num1, num2, num1 + num2) # This would output # 5 + 10 is equal to 15. The %f formatter is used to input float values, or numbers with values after the decimal place.


1 Answers

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.

like image 96
Dimitris Fasarakis Hilliard Avatar answered Sep 23 '22 13:09

Dimitris Fasarakis Hilliard