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

断了今生、忘了曾经 提交于 2020-05-29 05:07:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45112098/why-is-this-usage-of-python-f-string-interpolation-wrapping-with-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!