我有以下 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 字符串中应用浮点精度?