格式化字符串中括号不匹配:SyntaxError: f-string: unmatched ‘[‘或SyntaxError: f-string: closing parenthesis ‘}‘ doe

诸神缄默不语-个人CSDN博文目录

介绍格式化字符串(f-string)的博文我会稍后推出。

本文介绍在写f-string过程中会出现的两种语法错误,都是用于格式化的字符串的括号没有匹配上导致的。如果直接在代码中写出字符串,现在大多数IDE的自动识别错误功能都能识别出来;但是有时我们需要从文件中直接读取字符串,这种情况下可能出现类似这样的语法报错:
SyntaxError: f-string: unmatched '['
SyntaxError: f-string: closing parenthesis '}' does not match opening parenthesis '['

第一种情况的代码示例:

example_dict={"apple":"red","pineapple":"yellow"}
example_value=f'The value is {example_dict["apple"'

完整的报错信息:

(venv_name) D:\PythonCode>python trys\fbug.py
  File "D:\PythonCode\trys\fbug.py", line 2
    example_value=f'The value is {example_dict["apple"'
                                                       ^
SyntaxError: f-string: unmatched '['

第二种情况的代码示例:

example_dict={"apple":"red","pineapple":"yellow"}
example_value=f'The value is {example_dict["apple"}'

完整的报错信息:

(venv_name) D:\PythonCode>python trys\fbug.py
  File "D:\PythonCode\trys\fbug.py", line 2
    example_value=f'The value is {example_dict["apple"}'
                                                        ^
SyntaxError: f-string: closing parenthesis '}' does not match opening parenthesis '['

这两种情况下正确无错的写法显然都是:

example_dict={"apple":"red","pineapple":"yellow"}
example_value=f'The value is {example_dict["apple"]}'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值