是否可以一步将 f 字符串中的所有浮点数舍入为相同位数?

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

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

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

python string-formatting f-string
1个回答
0
投票

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

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

print('rounding constants: {}, {}, {}'.replace('{}','{:.2f}').format(math.pi, math.e, math.tau))
© www.soinside.com 2019 - 2024. All rights reserved.