为什么不能在f字符串中使用反斜杠? [英] Why isn't it possible to use backslashes in f-strings?
问题描述
在Python> = 3.6中,f字符串可用作str.format
方法的替代.举一个简单的例子,它们是等效的:
In Python >=3.6, f-strings can be used as a replacement for the str.format
method. As a simple example, these are equivalent:
'{} {}'.format(2+2, "hey")
f'{2+2} {"hey"}'
不管格式说明符,我基本上可以将f字符串中大括号内的str.format
位置参数.特别要注意的是,尽管看起来有点笨拙,但我只允许在其中输入str
文字.
Disregarding format specifiers, I can basically move the positional arguments of str.format
inside braces in an f-string. Note specifically that I am allowed to just put str
literals in here, although it may seem a bit unwieldy.
但是有一些限制.具体来说,任何形状或形式的反斜杠都不允许在其中f弦的花括号:
There are however some limitations. Specifically, backslashes in any shape or form are disallowed inside the braces of an f-string:
'{}'.format("new\nline") # legal
f'{"new\nline"}' # illegal
f'{"\\"}' # illegal
如果在括号内,我什至不能使用\
来分隔长行;
I cannot even use \
to split up a long line if it's inside the braces;
f'{2+\
2}' # illegal
即使在普通str
的内部完全允许使用\
,
even though this usage of \
is perfectly allowed inside normal str
's;
'{\
}'.format(2+2) # legal
在我看来,如果解析器在f字符串大括号内的所有位置都看到\
字符,则将硬停止编码到解析器中.为什么要实施此限制?尽管 docs 指定了此行为,但这并不能说明为什么
It seems to me that a hard stop is coded into the parser if it sees the \
character at all inside the braces of an f-string. Why is this limitation implemented? Though the docs specify this behavior, it does not justify why.
推荐答案
您似乎期望
'{}'.format("new\nline")
和
f'{"new\nline"}'
等同.这不是我所期望的,也不是f字符串中的反斜杠在Python 3.6的预发行版本中如何起作用的,其中允许在括号之间使用反斜杠.那时,您会收到一个错误消息,因为
to be equivalent. That's not what I would expect, and it's not how backslashes in f-strings worked back in the pre-release versions of Python 3.6 where backslashes between the braces were allowed. Back then, you'd get an error because
"new
line"
不是有效的Python表达式.
is not a valid Python expression.
如前所述,花括号中的反斜杠令人困惑且不明确,它们为已禁止以免引起混淆:
As just demonstrated, backslashes in the braces are confusing and ambiguous, and they were banned to avoid confusion:
这样做的目的是禁止像这样的复杂代码:
The point of this is to disallow convoluted code like:
>>> d = {'a': 4}
>>> f'{d[\'a\']}'
'4'
此外,我禁止将转义用于方括号,如:
In addition, I'll disallow escapes to be used for brackets, as in:
>>> f'\x7bd["a"]}'
'4'
(其中chr(0x7b)=="{").
(where chr(0x7b) == "{").
这篇关于为什么不能在f字符串中使用反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!