Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this usage of python F-string interpolation wrapping with quotes?

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?

like image 552
Connor Clark Avatar asked Jul 14 '17 21:07

Connor Clark


People also ask

Do F strings need double quotes?

4.1.We can use any quotation marks {single or double or triple} in the f-string.

What is Python string interpolation?

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.

Why is f string used in Python?

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.

Which character should be used for string interpolation Python?

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.


1 Answers

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 stringification of a set uses the repr of its elements, which is where the quotes come from.

like image 57
jwodder Avatar answered Nov 14 '22 21:11

jwodder