Python 3.12前VSCode中f-string嵌套引号的Pylance错误解决
修复你的Python代码错误
你的代码存在两个问题:
- f-string嵌套引号冲突:Python 3.12版本之前,f-string内部不能使用和外层相同的引号,否则会被解析为字符串结束标记,触发语法错误。
- 字典键名不匹配:你定义的字典中存储主人姓名的键是
owner-name,但打印代码里写的是owner,运行时会抛出KeyError。
具体修复方案
方法1:内层改用单引号
将f-string内部的双引号替换为单引号,避免和外层引号冲突:
pet1 = { "name": "Phal", "owner-name": "Mouin" } pet2 = { "name": "Phil", "owner-name": "Saoum" } pet3 = { "name": "Pham", "owner-name": "Mukti" } pets = [pet1, pet2, pet3] for pet in pets: print(f"The name of the pet is {pet['name']} and the owner is {pet['owner-name']}")
方法2:外层改用单引号
把整个f-string的外层引号换成单引号,内层保留双引号:
for pet in pets: print(f'The name of the pet is {pet["name"]} and the owner is {pet["owner-name"]}')
不推荐的方法:使用转义符
虽然可以用\转义内层引号,但会降低代码可读性,不建议使用:
for pet in pets: print(f"The name of the pet is {pet[\"name\"]} and the owner is {pet[\"owner-name\"]}")
注意:无论用哪种方法,都要把pet["owner"]修正为pet["owner-name"],否则运行时会因找不到对应键报错。
内容的提问来源于stack exchange,提问作者sakibmouin
相关产品推荐
相关产品推荐

