简体   繁体   English

除去小数点以外的所有零小数位

[英]Remove all zero decimal places except the decimal mark

I'd like to format a string that has only zeros after the decimal mark: Example: 12.000 to 12. 我想格式化一个在小数点后仅包含零的字符串:例如: 12.00012.

Any ideas? 有任何想法吗? Thanks 谢谢

If you only want to strip zeroes: 如果只想去除零:

>>> '12.000'.rstrip('0')
'12.'

You can use format : 您可以使用format

>>> s = "12.000"
>>> "{0:.3}".format(s)
12.

You may use regex: 您可以使用正则表达式:

import re
s = '12.00'
re.sub(r'(.+)\.0+$',r'\1.',s)
>>> '12.'

It depends on what you are looking for. 这取决于您要寻找的东西。 If you need the "." 如果需要“。” after "12" ala "12.", use the other answers. 在“ 12” ala“ 12.”之后,使用其他答案。

If you don't care about the dot, but just want to display the digits of your number, use this: 如果您不关心点,而只想显示数字,请使用以下命令:

print('{0:1g}'.format(12.0000))

The "". “”。 will be there, it's still a float, you just can't see it with this method, which is different from the other ones. 会在那里,它仍然是一个浮点数,您只能通过此方法看不到它,这与其他方法不同。 Also, this answer works in Python 3.x, not in Python 2.x. 另外,此答案在Python 3.x中有效,而在Python 2.x中无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM