Search code examples
pythonpython-3.6specificationsstring-interpolationf-string

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?


Solution

  • 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.