小编NoS*_*ock的帖子

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

我有以下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精度?

python python-3.x f-string

9
推荐指数
1
解决办法
262
查看次数

标签 统计

f-string ×1

python ×1

python-3.x ×1