受报价影响的F弦
alien_o = {"Colour" : "Green"}
print(f"The colour is now {alien_o["Colour"]}.")
这些代码行怎么了?闭合支架和卷发支架受引号的影响,我不明白为什么。
alien_o = {"Colour" : "Green"}
print(f"The colour is now {alien_o["Colour"]}.")
What's wrong with these lines of code? The closing bracket and the curly bracket is affected by the quotes, and I don't understand why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
混合
“
,尝试使用'color'
而不是“ color”
。。它 “现在的颜色为{alien_o [,这不是您想要
的
。 /whatsnew/3.12.html#whatsnew312-pep701“ rel =“ nofollow noreferrer”> python 3.12 ,OP发布的现在是有效的语法。具体来说,这是新的:这是新的:
It mixes up the
"
, try using'Colour'
instead of"Colour"
.Because it thinks that the format string is
f"The colour is now {alien_o["
, which is not what you want.Python 3.12 and later
As of Python 3.12, what OP posted is now valid syntax. Specifically, this is new:
直率的答案:
f-strings使用引号作为定界数,这就是为什么在interpolated元素中包含引号{}将解释器混淆的原因。 Python认为您可能正在尝试用内部行情结束F弦。
,如果您关心错误的语义,实际上它不是受影响的关闭括号,而是您的{variable}将其切成一半。
结果,这是一个早期的部分:
由print()解释为字符串,因为它在技术上被引号包裹,而不是dict键插值(插入)插入F弦,您可能意图将其包裹在{}中。
但是,python不知道该消息的 rets ,并在它可以做其他任何事情之前就引出错误。
这就是为什么您可能会看到:
一个可能的解决方案:
如果您问我,在您的情况下,克服这种困惑的最直接方法是消除对引号的需求。
如果那是仍然不满意的话,它不必感觉那么简单:
上面我使用列表理解来添加潜在标准,然后将其传递给一个键 F弦。
您也可以研究:
喜欢在F弦上的一个时期:
注释的底线将出于与您上面的代码相同的原因而失败。
Straight-forward answer:
f-strings use quotation marks as delimiters, which is why including quotes in the interpolated element {} confuses the interpreter. Python thinks that you may be trying to end the f-string with the interior quotes.
If you care about the semantics of the error, it's actually not the closing bracket that's affected, but rather your {variable} is chopped in half.
As a result, this earlier part:
is interpreted by print() as a string since it is technically wrapped by quotes, as opposed to a dict key interpolated (inserted) into a f-string, which was likely your intent in wrapping it with {}.
However, python doesn't know what to do with the rest of the message, and throws an error before it can do anything else.
That's why you are likely seeing:
One possible solution:
If you ask me, in your case the most straightforward way to overcome this confusion is to eliminate the need for quotation marks.
If that's still not satisfying, it doesn't have to feel so plain jane:
Above I used a list comprehension to add potential criteria to the keys variable before passing it to an f-string.
You can also look into:
One example of calling the ASCI character code of a period in an f-string:
The commented-out bottom line would would fail for the same reason as your code above.