为什么我不能在F弦中嵌入字符串字符串?

发布于 2025-01-17 10:36:04 字数 290 浏览 0 评论 0原文

代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沐歌 2025-01-24 10:36:04

您必须使用现场中的单个引号以外的其他内容。

print(f'Age : {tinydict.get("Age")}')

作为字符串的字面文字,必须在词汇分析中识别整个表达式,并且词汇分析仪在看到{时就不足以启动新的引用“上下文”。结果,它将其视为

f'Age {tinydict.get('

完整的字符串文字,然后是标识符tinydict,产生语法错误。

You have to use something other than single quotes in the field.

print(f'Age : {tinydict.get("Age")}')

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 sees

f'Age {tinydict.get('

as a complete string literal, followed by the identifier tinydict, which produces the syntax error.

吖咩 2025-01-24 10:36:04

从Python 3.12开始,您可以: pep 701 指定了启用此功能的更改。

在以前的版本中,这是不可能的。 pep 498解释

由于python的字符串令牌规则,f-string f'abc {a ['x']} def'无效。 Tokenizer将其解析为3个令牌:f'abc {a ['x']} def'。就像普通字符串一样,不能通过使用原弦来解决。有多种编写此F弦的正确方法:具有不同的引用字符:

  f“ abc {a ['x']} def”
 

或带有三引号:

  f'''abc {a ['x']} def''''
 

语法后面的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:

Due to Python’s string tokenizing rules, the f-string f'abc {a['x']} def' is invalid. The tokenizer parses this as 3 tokens: f'abc {a[', x, and ']} def'. Just like regular strings, this cannot be fixed by using raw strings. There are a number of correct ways to write this f-string: with a different quote character:

f"abc {a['x']} def"

Or with triple quotes:

f'''abc {a['x']} def'''

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文