我有一个很长的 f 字符串,其中包含许多浮点值,我想将所有这些值四舍五入到相同的位数。有没有一种方法可以一次性或以一种聪明的方式做到这一点,或者我是否需要分别指定每个数字?
我知道我可以使用
舍入 f 字符串中的值print(f"pi rounded to 2 decimals is {math.pi:.2f}")
但是,我想做一些类似的事情:
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"
但这对我来说似乎有点迂回,我想知道是否有更直接的方法来做到这一点。
(已编辑:我编辑了问题以澄清我并不真正关心在一步中执行此操作,而只是想找到一种比单独为每个浮动指定它更智能的方法)
没有默认格式,但您可以在字符串上使用
re.sub
s = f"rounding pi and tau and e to 2 digits results in {math.pi}, {math.tau}, {math.e}, respectively:"
s = re.sub(r'\d+\.\d+', lambda x: f"{float(x.group()):.2f}", s)
输出
rounding pi and tau and e to 2 digits results in 3.14, 6.28, 2.72, respectively: