花括号内部的f-string公式不起作用

13

我正在使用Python 3.7。

我在第三行的代码可以正常工作,但是当我将底层公式插入第四行时,我的代码返回错误:

SyntaxError: f-string: mismatched '(', '{', or '[' (该错误指向第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行有什么问题。


9
在花括号内使用单引号 print(f"2: {format(round(cheapest_plan_point), ',')}") - Space Impact
1个回答

20

你在一个用"..."包裹的字符串中使用了"引号。

Python看到的是:

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

所以)}是一个新的、独立的字符串

使用不同的分隔符:

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

然而,在这里你不需要使用format()。在f-string中,你已经在对每个插值的值进行格式化了!只需添加:,即可将格式化指令直接应用于round()结果:

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

{expression:formatting_spec} 格式将 formatting_spec 应用于 expression 的结果,就像使用 {format(expression, 'formatting_spec')} 一样,但是不需要调用 format() 函数,也不需要将 formatting_spec 部分用引号括起来。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接