为什么在Python 3.6中评估f"\ {10}"时符号"{"仍然存在?

laz*_*zis 13 python python-3.x python-3.6 f-string

f-string是Python 3.6中的新功能之一.

但是,当我尝试这个:

>>> f"\{10}"
'\\{10'
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么左大括号'{'保留在结果中.我认为结果应该与str.format:

>>> "\{}".format(10)
'\\10'
Run Code Online (Sandbox Code Playgroud)

PEP-0498中,它没有明确回答这个问题.那么是什么原因导致左大括号'{'留在结果和是什么原因导致之间的差异f-stringstr.format()

Jim*_*ard 13

这是一个错误.目前工作的一个方法是使用Unicode文本\u005c\,而不是:

>>> f'\u005c{10}'
'\\10'
Run Code Online (Sandbox Code Playgroud)

或者,具有类似的效果,使用raw f-string:

>>> rf'\{10}'
'\\10'
Run Code Online (Sandbox Code Playgroud)

通过使用'\'它似乎两个奇怪的事情同时发生:

  • 下一个字符('{'此处)已转义,将其保留在结果字符串中.
  • 还会评估格式化的字符串,这是奇怪的而不是预期的

例证:

>>> f'\{2+3}'
'\\{5'
>>> a = 20
>>> f'\{a+30}'
'\\{50'
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,我都会尽快填写错误报告(因为我看到你还没有),并在收到回复时更新.

更新:创建问题29104 -如果您感兴趣,请查看那里的对话,左括号将保留在格式字符串结果中.

更新2:使用PR 490解决问题.