为什么我不能在F弦中嵌入字符串字符串?
代码:
tinydict = {'Name': 'Runoob', 'Age': 27}
# print ("Age : %s" % tinydict.get('Age')) # can display correctly
print(f'Age : {tinydict.get('Age')}')
输出:
语法错误:语法无效
为什么?
Code:
tinydict = {'Name': 'Runoob', 'Age': 27}
# print ("Age : %s" % tinydict.get('Age')) # can display correctly
print(f'Age : {tinydict.get('Age')}')
Output:
SyntaxError: invalid syntax
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用现场中的单个引号以外的其他内容。
作为字符串的字面文字,必须在词汇分析中识别整个表达式,并且词汇分析仪在看到
{
时就不足以启动新的引用“上下文”。结果,它将其视为完整的字符串文字,然后是标识符
tinydict
,产生语法错误。You have to use something other than single quotes in the field.
As a string literal, the entire expression has to be recognized during lexical analysis, and the lexical analyzer isn't sophisticated enough to start a new quoting "context" when it sees the
{
. As a result, it seesas a complete string literal, followed by the identifier
tinydict
, which produces the syntax error.从Python 3.12开始,您可以: pep 701 指定了启用此功能的更改。
在以前的版本中,这是不可能的。 pep 498解释:
语法后面的tokenizer是在文档中解释。如您所见,在Lexing阶段,解析器没有试图判断引用字符是否可能属于某些嵌套的字符串。它只是找到了与开头报价相匹配的第一个非排放序列,并考虑了字符串的末端。
换句话说,Python解析器首先确定F弦的边界在哪里,并且后来才能将嵌入在内部的表达式解析。
As of Python 3.12, you can: PEP 701 specified the change that enabled this.
In previous versions, this was not possible. PEP 498 explains:
The grammar followed by the tokenizer is explained in the documentation. As you can see, at the lexing stage the parser does not attempt to tell whether a quote character might belong to some nested string. It just finds the first non-escaped sequence that matches the opening quote and considers that the end of the string.
Put another way, the Python parser first determines where the boundaries of the f-string are, and only later proceeds to parse the expressions embedded inside.