简体   繁体   中英

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.

Any ideas? Thanks

If you only want to strip zeroes:

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

You can use 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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