regex help

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Mar 13 20:48:19 EDT 2015


Larry Martell wrote:

> I need to remove all trailing zeros to the right of the decimal point,
> but leave one zero if it's whole number. 


def strip_zero(s):
    if '.' not in s:
        return s
    s = s.rstrip('0')
    if s.endswith('.'):
        s += '0'
    return s


And in use:

py> strip_zero('-10.2500')
'-10.25'
py> strip_zero('123000')
'123000'
py> strip_zero('123000.0000')
'123000.0'


It doesn't support exponential format:

py> strip_zero('1.2300000e3')
'1.2300000e3'

because it isn't clear what you intend to do under those circumstances.


-- 
Steven




More information about the Python-list mailing list