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

NoS*_*ock 9 python python-3.x f-string

我有以下f-string我想在变量可用的条件下打印出来:

f"Percent growth: {self.percent_growth if True else 'No data yet'}"
Run Code Online (Sandbox Code Playgroud)

结果如下:

Percent growth : 0.19824077757643577
Run Code Online (Sandbox Code Playgroud)

所以我通常会使用类型说明符来表示float精度:

f'{self.percent_growth:.2f}'
Run Code Online (Sandbox Code Playgroud)

这将导致:

0.198
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,这与if语句混淆了.它失败的原因是:

f"Percent profit : {self.percent_profit:.2f if True else 'None yet'}"
Run Code Online (Sandbox Code Playgroud)

if语句变得无法访问.或者以第二种方式:

f"Percent profit : {self.percent_profit if True else 'None yet':.2f}"
Run Code Online (Sandbox Code Playgroud)

只要条件导致else子句,f-string就会失败.

所以我的问题是,当f-string可以产生两种类型时,如何在f-string中应用float精度?

Nik*_*nar 10

你可以使用另一个f-string作为你的第一个条件:

f"Percent profit : {f'{self.percent_profit:.2f}' if True else 'None yet'}"
Run Code Online (Sandbox Code Playgroud)

诚然不理想,但它确实起作用.

  • 另一种方法是使用“ str.format”,但我认为这没有什么不同。f“利润百分比:{'{:.2f}'。format(self.percent_format)如果为True else'None yet'}”`这很简单,只要OP坚持将条件放在f字符串本身内即可。 (2认同)