介绍格式化字符串(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"]}'