如何在条件 f 字符串中应用浮点精度(类型说明符)?

How to apply float precision (type specifier) in a conditional f-string?

我有以下 f 字符串,我想在变量可用的情况下打印出来:

f"Percent growth: {self.percent_growth if True else 'No data yet'}"

这导致:

Percent growth : 0.19824077757643577

所以通常我会像这样使用浮点精度的类型说明符:

f'{self.percent_growth:.2f}'

这将导致:

0.198

但是在这种情况下,这与 if 语句混淆了。要么失败,因为:

f"Percent profit : {self.percent_profit:.2f if True else 'None yet'}"

if 语句变得不可访问。 或者第二种方式:

f"Percent profit : {self.percent_profit if True else 'None yet':.2f}"

只要条件导致 else 子句,f 字符串就会失败。

所以我的问题是,当 f 字符串可以产生两种类型时,如何在 f 字符串中应用浮点精度?

您可以为您的第一个条件使用另一个 f 字符串:

f"Percent profit : {f'{self.percent_profit:.2f}' if True else 'None yet'}"

不可否认,这并不理想,但它确实起作用了。

我认为 f string answer 中的 f string 非常简单,但如果您想要更多可读性,请考虑将条件 移到 f 字符串之外:

value = f'{self.percent_profit:.2f}' if True else 'No data yet'
print(f"Percent profit : {value}")

您也可以为格式化程序使用三元组 - 无需像 那样堆叠 2 个 f 字符串:

for pg in (2.562345678, 0.9, None):   # 0.0 is also Falsy - careful ;o)
    print(f"Percent Growth: {pg if pg else 'No data yet':{'.05f' if pg else ''}}")
    # you need to put '.05f' into a string for this to work and not complain

输出:

Percent growth: 2.56235
Percent growth: 0.90000
Percent growth: No data yet