Search code examples
stringpython-2.7zero

Removing zeros from a numeric string in Python


Suppose i have numeric string. I would like to remove all the trailing zeros and also the decimal point if necessary. For example -

'0.5' -> '.5'
'0005.00' -> '5'

I used this method :

s.strip("0") # where 's' contains the numeric string.

But for the 0005.00, it returns 5., so how would i remove the decimal point if necessary.


Solution

  • To achieve this you could write a little function

    def dostuff(s):
        s = s.strip('0')
        if len(s) > 0 and s[-1] == '.':
            s = s[:-1]
        return s
    

    This strips all the 0s and if a . was found and it was at the end of the string (meaning its the decimal point and nothing follows it) it will strip that too using [s:-1] (this strips the last character).

    s[-1] gets the last character of the string. With this we can check if . is the last character.

    This may be achieved with less code using a regex, but I think this is easier to follow

    Demo

    >>> print dostuff('5.0')
    5
    >>> print dostuff('005.00')
    5
    >>> print dostuff('.500')
    .5
    >>> print dostuff('.580')
    .58
    >>> print dostuff('5.80')
    5.8