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()
?
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!
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.
%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.
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.
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:
'{'
here) was escaped, leaving it in the resulting string. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With