一步将 f 字符串中的所有浮点数四舍五入为相同位数的简单方法是什么?

问题描述 投票:0回答:2

我有一个很长的 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"

但这对我来说似乎有点迂回,我想知道是否有更直接的方法来做到这一点。

(已编辑:我编辑了问题以澄清我并不真正关心在一步中执行此操作,而只是想找到一种比单独为每个浮动指定它更智能的方法)

python string-formatting f-string
2个回答
3
投票

我不认为有内置的方法可以做到这一点,但您可以将

.replace
方法与
.format
方法结合使用,以避免重复
:.2f

print('rounding constants: {}, {}, {}'.replace('{}','{:.2f}').format(math.pi, math.e, math.tau))

1
投票

没有默认格式,但您可以在字符串上使用

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:
© www.soinside.com 2019 - 2024. All rights reserved.