为什么不能在 python f 字符串中添加引号?
为什么 f'{'one'}'
语法无效?在我看来,如果 f 字符串是明智的,那么一旦 {
出现,{ ... }
内部的所有内容都应该被视为 Python 代码。
语言设计者决定将字符串的结束引号视为字符串结束的原因是什么,即使是在 { ... }
内部?
由此带来什么好处?
关闭后编辑
注意:这是一个老问题。从 python 3.12 开始,这实际上是有效的语法。请参阅:https://docs.python.org/3/whatsnew/ 3.12.html#whatsnew312-pep701
Why is f'{'one'}'
invalid syntax? Seems to me like if f-strings were sensible, as soon as a {
appears, everything inside of { ... }
should be considered Python code.
What's the reason the language designers decided to make the string's end quote be considered as a string end, even inside of { ... }
?
What advantages come from this?
Post-close edit
NOTE: This is an old question. From python 3.12 this is actually valid syntax. See: https://docs.python.org/3/whatsnew/3.12.html#whatsnew312-pep701
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

https://peps.python.org/pep-0498/#escape-sequences
为什么他们不“修复”分词器以使其成为可能?可能向后兼容。当一个简单的解决方法是在常见情况下简单地在
'
中混合"
时,这可能是不值得的。语法之所以如此,是因为语言是构建在由语法定义的块(令牌)上,该语法显示了 Python 的 f 字符串重用了两个现有构建块。首先,
f'
和尾随之间的所有内容。'
是有效的字符串内容. 如果删除f
,您的 Python 程序的语法仍然正确(尽管字符串的内容不是动态的)。 /code> 不满足此条件第二个条件是代码。{
和}
之间是 一个有效的 Python 表达式。'one'
是一个有效的表达式,但它必须同时满足两个条件。下一个替代\'one\'
是一个有效的字符串文字 但是它是一个无效的表达式(无法在 REPL 中粘贴\'one\'
,例如) - 所以它也不会通过这两个条件。更改此设置将使 f 字符串在解析器中采用不同的路径,并且可能需要以前不需要的重复代码。有关标记化、语法和编译器设计的更多详细信息超出了本简短答案的范围。https://peps.python.org/pep-0498/#escape-sequences
Why didn't they "fix" the tokenizer to make it possible? Possibly backwards compatibility. Possibly it just isn't worth it when an easy fix is to simply mix
"
inside'
for the common cases.The reason the syntax acts like it does is that languages are built upon blocks (tokens) defined by a grammar that shows how tokens are built. Python's f-strings reused two existing building blocks. First, everything between the
f'
and trailing'
are valid string contents. If you remove thef
, your Python program's syntax will still be correct (though the contents of the string will not be dynamic). Your example,'{'one'}'
fails this condition. The second condition is that the code between{
and}
is a valid Python expression.'one'
is a valid, expression, but it must pass both conditions. The next alternative\'one\'
is a valid string literal but it's an invalid expression (cannot paste\'one\'
in the REPL, for example) - so it doesn't pass both conditions, either. Changing this would make f-strings take a different path through the parser and probably require duplicate code where it wasn't needed before. More detail on tokenization, grammars, and compiler design is beyond the scope of this short answer.