6

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?

Granny Aching
  • 1,295
  • 12
  • 37
Connor Clark
  • 671
  • 7
  • 15
  • 2
    Your link to 2.7 doc will not have anything about a 3.6 feature. Instead, https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings – Terry Jan Reedy Jul 14 '17 at 22:08

1 Answers1

10

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.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • 1
    Nested {}s are recognized as a nested replacement field only in the optional format specification (after ':'). That they have their normal meaning in the replacement expression, and result in a set, can be verified by executing `print(f'{ { {a} } }')` – Terry Jan Reedy Jul 14 '17 at 22:24