大括号内的f字符串公式不起作用

时间:2018-10-03 13:03:09

标签: python f-string

我使用的是Python 3.7。

我在第3行的代码工作正常,但是当我将基础公式插入第4行时,我的代码返回错误:

语法错误:f字符串:不匹配的'(','{'或'[' (错误指向第4行中的第一个'('。

我的代码是:

cheapest_plan_point = 3122.54
phrase = format(round(cheapest_plan_point), ",")
print(f"1: {phrase}")
print(f"2: {format(round(cheapest_plan_point), ",")}")

我不知道第4行出了什么问题。

1 个答案:

答案 0 :(得分:6)

您在"分隔字符串中使用了"..."引号。

Python看到:

print(f"2: {format(round(cheapest_plan_point), "
      ,
      ")}")

因此)}是一个单独的新字符串

使用不同的分隔符:

print(f"2: {format(round(cheapest_plan_point), ',')}")

但是,您无需在此处使用format() 。在f字符串中,您已经在格式化每个插值值!只需添加:,即可将格式设置说明直接应用于round()结果:

print(f"2: {round(cheapest_plan_point):,}")

格式{expression:formatting_spec}formatting_spec应用于expression的结果,就像您使用{format(expression, 'formatting_spec')}一样,但是不必调用format()并且不必将formatting_spec部分加引号。

相关问题