如何在Python的fstring中跳过小数点后的零?

2024-05-01 21:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的f字符串中设置一个精度,但我不想在小数部分设置尾随的零

i = 1002
print(f'{i/1000:.2f}') # 1.00 but this must be 1

i = 1009
print(f'{i/1000:.2f}') # 1.01, this is correct

第一个print必须是1,我的预期行为可以在第二个print中看到,它是1.01

我尝试了:g,但第一个print有效,但第二个失败

i = 1000
print(f'{i/1000:.2g}') # 1, this is correct but
i = 1009
print(f'{i/1000:.2g}') # 1, but this must be 1.01

我试过的一种方法是f'{i/1000:.2f}'.strip('.0'),但我想知道是否有更好的方法

编辑:

在我的实际代码中,如果i100000,那么分母也将是100000(在i的顺序中最小的数字),换句话说,我代码中的分母将始终是这样的:i//分母将始终产生一个数字


Tags: 方法字符串代码is精度数字bethis
2条回答

如果字符串只有浮点数,那么可以使用^{}而不是现在使用的^{})。此外,您需要首先使用'0'对它进行链式调用,然后使用'.'like .rstrip('0').rstrip('.')来处理带有尾随零的整数,如10000

但是,如果您可以在字符串中包含其他字符,并且只想为数字去除0,则可以使用嵌套的f-string作为:

>>> f"{f'{1002/1000:.2f}'.rstrip('0').rstrip('.')} number"
'1 number'

>>> f"{f'{1009/1000:.2f}'.rstrip('0').rstrip('.')} number"
'1.01 number'

>>> f"{f'{1000:.2f}'.rstrip('0').rstrip('.')} number"
'1000 number'

您必须使用两种不同格式的字符串和round来检测何时使用它们:

for i in [1002, 1009]:
    print(f'{i/1000:.0f}') if round(i/1000, 2) == 1.00 else print(f'{i/1000:.2f}')

这将产生:

1
1.01

请参阅Format Specification Mini-Language

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.

取决于你的品味,是使用我建议的round方法还是你提到的strip方法。如果您以代码应该清晰、简洁和可维护的方式理解Pythonic,那么我将使用round方法处理两种格式的字符串,因为这对于未来的开发人员来说是非常可读/可理解的

相关问题 更多 >