Python 中 SyntaxError: f-string: unmatched '(' 错误
Python "SyntaxError: f-string: unmatched '('" 当我们在用双引号包裹的 f-string
中使用双引号时会发生。要解决这个错误,请确保将 f-string
包裹在单引号中,如果 它包含双引号,反之亦然。
下面是一个产生上述错误的示例代码
name = 'Alice'
# ⛔️ SyntaxError: f-string: unmatched '('
print(f"employee: {name.replace("Alice", "Bob")}")
我们将 f
字符串用双引号括起来,但字符串本身在表达式中包含双引号。
要解决错误,请替换引号。 例如,如果 f
字符串包含双引号,则将其用单引号引起来。
name = 'Alice'
# 👇️ employee: Bob
print(f'employee: {name.replace("Alice", "Bob")}')
相反,如果字符串包含单引号,则将其用双引号括起来。
name = 'Alice'
# 👇️ employee: Bob
print(f"employee: {name.replace('Alice', 'Bob')}")
如果我们的 f
字符串同时包含双引号和单引号,则可以使用三引号字符串。
name = 'Alice'
# 👇️ employee's name: Bob
print(f"""employee's name: {name.replace("Alice", "Bob")}""")
错误的另一个常见原因是左括号和右括号不匹配。
name = 'Alice'
# ⛔️ SyntaxError: f-string: unmatched ')'
my_str = f'employee: {name)'
我们用大括号打开表达式块,但以导致错误的括号结束。
表达式块需要使用大括号打开和关闭。
name = 'Alice'
my_str = f'employee: {name}'
print(my_str) # 👉️ employee: Alice
如果我们尝试访问字典中的键或列表中的项目,请使用方括号。
emp = {'name': 'Alice'}
my_str = f"employee: {emp['name']}"
print(my_str) # 👉️ employee: Alice
格式化字符串文字 f-strings
让我们通过在字符串前面加上 f
来在字符串中包含表达式。
my_str = 'is subscribed:'
my_bool = True
result = f'{my_str} {my_bool}'
print(result) # 👉️ is subscribed: True
确保将表达式包裹在花括号 - {expression}
中。
总结
Python "SyntaxError: f-string: unmatched '('" 当我们在用双引号包裹的 f-string 中使用双引号时会发生。要解决这个错误,请确保将 f-string 包裹在单引号中,如果 它包含双引号,反之亦然。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。