相关疑难解决方法(0)

根据条件使用格式的f-string

如何使用带有逻辑的f-string格式化intfloat?我想pplTrue格式化num为2位小数,如果pplFalse格式化为它是什么.

有点像string = f'i am {num:.2f if ppl else num}'但这不起作用.下面的代码演示了如果可能的话我想用更简单的f字符串实现的行为:

ppl = True
num = 3
string = f'I am {num:.2f}' if ppl else f'I am {num}'
print(string)
#if ppl False
#=> i am 3
#if ppl True
#=> i am 3.00
Run Code Online (Sandbox Code Playgroud)

python python-3.x f-string

9
推荐指数
2
解决办法
5479
查看次数

标签 统计

f-string ×1

python ×1

python-3.x ×1