我有一个很长的 f 字符串,其中包含许多浮点值,我都想四舍五入到相同的位数。有没有一种方法可以一次性完成此操作,或者我是否需要立即指定整个 f 字符串的数字?
我知道我可以使用
f"pi rounded to 2 decimals = {math.pi:.2f}'"
对 f 字符串中的值进行舍入
但是,我想做一些类似的事情:
print(f"rounding pi and tau and e to 2 digits results in {math.pi}, {math.tau}, {math.e}, respectively:"<some operation to round all to two digits.>)
注意,这只是一个最小的例子。实际上,我的字符串有更多与之相关的浮点数(并且不仅仅是一个数学常数列表。
我知道我可以做这样的事情:
constants = [math.pi, math.tau, math.e]
rounded_constants = [str(round(c, 2)) for c in constants]
print(f"rounding pi and tau and e to 2 digits results in {rounded_constants[0]}, {rounded_constants[1]}, {rounded_constants[2]}, respectively"
但这对我来说似乎有点迂回,我想知道是否有更直接的方法来做到这一点。