f-字符串受引号影响[重复]

问题描述 投票:0回答:2
alien_o = {"Colour" : "Green"}
print(f"The colour is now {alien_o["Colour"]}.")

这几行代码有什么问题?右括号和大括号受引号影响,我不明白为什么。

python python-3.6 f-string
2个回答
4
投票

它混淆了

"
,请尝试使用
'Colour'
而不是
"Colour"

因为它认为格式字符串是

f"The colour is now {alien_o["
,这不是你想要的。

Python 3.12 及更高版本

Python 3.12 开始,OP 发布的语法现在是有效的。具体来说,这是新的:

引号重用:在Python 3.11中,重用与封闭的f字符串相同的引号会引发语法错误,迫使用户使用其他可用的引号(例如,如果f字符串使用单引号,则使用双引号或三引号)。在 Python 3.12 中,你现在可以做这样的事情


0
投票

直接回答:

f 字符串使用引号作为分隔符,这就是为什么在插值元素 {} 中包含引号会让解释器感到困惑。 Python 认为您可能试图用内部引号结束 f 字符串。

右括号和大括号受引号影响

如果您关心错误的语义,实际上受影响的不是右括号,而是您的 {variable} 被切成两半。

因此,前面的部分:

The colour is now {alien_o[

被 print() 解释为字符串 因为它在技术上是用引号括起来的 ,而不是插入(插入)到 f 字符串中的 dict 键,这可能是您用 {} 括起来的意图。

但是,python 不知道如何处理消息的 rest,并且在执行其他操作之前会抛出错误。

这就是为什么您可能会看到:

SyntaxError: f-string: unmatched '['

一种可能的解决方案:

如果你问我,在你的情况下,克服这种混乱的最直接方法就是消除对引号的需要。

alien_o = {"Colour" : "Green"}
key = "Colour"
print(f"The colour is now {alien_o[key]}.")

# or, if you want to make it more generalized:
print(f"The {key} is now {alien_o[key]}.")

如果那仍然不令人满意,它不必感觉如此简单简:

alien_o = {"Colour" : "Green", 
           "Face" : "Toothy", 
           "Shape" : "None", 
           "Transparency" : "Opaque"}

# dict.keys() gets all dict keys for you
# alien_o is your dict, so for you it is alien_o.keys()

keys = [i for i in alien_o.keys() if len(i)<7]
print(f"The alien's features are now {[alien_o[key] for key in keys]}.")

上面我使用了列表理解来将潜在的条件添加到键变量之前将其传递给 f 字符串。

您还可以查看:

  • 替代 Python 字符串插值方法
  • 其他有争议字符的asci代码(换行符,为f字符串中的简单函数指定字符串(我个人最喜欢)

调用 f 字符串中句点的 ASCI 字符代码的一个示例:

filename = 'file.txt'
print(f'The name of the file without extension is {filename.split(chr(46)})[0]
# print(f'The name of the file without extension is {filename.split('.'})[0] 

注释掉的底线将因与上面的代码相同的原因而失败。

© www.soinside.com 2019 - 2024. All rights reserved.