根据条件使用带有格式的f字符串 [英] Using f-string with format depending on a condition

查看:72
本文介绍了根据条件使用带有格式的f字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用带有逻辑的f字符串将int格式化为float?我想如果pplTrue来格式化num到小数点后两位,并且pplFalse来将其格式化为任何形式.

How can I use f-string with logic to format an int as a float? I would like if ppl is True to format num to 2 decimal places, and if ppl is False to rformat it as whatever it is.

类似string = f'i am {num:.2f if ppl else num}'的方法,但这不起作用.下面的代码演示了我想通过尽可能简单的f字符串实现的行为:

Something like string = f'i am {num:.2f if ppl else num}' but this does not work. The below code demonstrates the behaviour that I want to achieve with a simpler f-string if possible:

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

推荐答案

您可以嵌套表达式以对f字符串中的表达式求值.这意味着您可以在f字符串内向右移动三进制:

You can nest expressions to evaluate inside expressions in an f-string. This means you can move the ternary right inside your f-string:

string = f'I am {num:{".2f" if ppl else ""}}'

请注意嵌套所需的另一对大括号.

Note the additional pair of braces needed for nesting.

但是我认为这不是更清洁.就个人而言,与您清晰的原始版本相比,我很难解析这里发生的事情.毕竟简单胜于复杂;扁平比嵌套更好.

But I don't think this is cleaner. Personally I find it harder to parse what's going on here, as opposed to your clear original version. After all simple is better than complex; flat is better than nested.

这篇关于根据条件使用带有格式的f字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆