Code in question:
a = 'test'
# 1)
print(f'{a}') # test
# 2)
print(f'{ {a} }') # {'test'}
# 3)
print(f'{{ {a} }}') # {test}
My question is, why does case two print those quotes?
I didn't find anything explicitly in the documentation. The closest thing I found detailing this was in the PEP for this feature:
(the grammar for F-strings)
f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
The expression is then formatted using the format protocol, using the format specifier as an argument. The resulting value is used when building the value of the f-string.
I suppose that the value of a
is being formatted with some formatter, which, since the data type is a string, wraps it with quotes. This result is then returned to the surrounding F-string formatting instance.
Is this hypothesis correct? Is there some other place which documents this more clearly?
4.1.We can use any quotation marks {single or double or triple} in the f-string.
String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.
There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator.
In f'{ {a} }'
, the {a}
(as indicated by the grammar) is interpreted as a Python expression. In Python, {a}
constructs a set
of one element (a
), and the str
ingification of a set uses the repr
of its elements, which is where the quotes come from.
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