10

我有以下 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-string 就会失败。

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

4

3 回答 3

11

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

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

诚然,不理想,但它的工作。

于 2019-03-01T17:59:48.510 回答
2

您也可以对格式化程序使用三元 - 无需像Nikolas answer那样堆叠 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
于 2019-03-01T18:50:38.223 回答
2

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

value = f'{self.percent_profit:.2f}' if True else 'No data yet'
print(f"Percent profit : {value}")
于 2019-03-01T18:12:41.403 回答