Replace string with python

I am using python 2.7. I need to replace the line "0"

at the end.

say a = "2.50"

 a = a.replace('0', '')

      

I get a = 2.5. I am fine with this result.

Now a = "200"

 a = a.replace('0', '')

      

I get a = 2 and this by design I agreed. But I am expecting a = 200 output.

In fact, what I'm looking for is

when any value after the decimal point at the end, "0"

replace "0"

with the value None.

Below are examples and I am awaiting results.

IN: a = "200" 
Out: a = 200
In: a = "150"
Out: a = 150
In: a = 2.50
Out: a = 2.5
In: a = "1500"
Out: a = 1500
In: a = "1500.80"
Out: a = 1500.8
In: a = "1000.50"
Out: a = 1000.5

      

Not a value is a string.

Note: for a while a = 100LL

or a = 100.50mt

.

+3


source to share


3 answers


You can do this using a regular expression:

import re

rgx = re.compile(r'(?:(\.)|(\.\d*?[1-9]\d*?))0+(?=\b|[^0-9])')

b = rgx.sub('\2',a)

      

Where b

is the result of removing trailing zeros after the decimal point from a

.

We can write this in a nice function:



import re

tail_dot_rgx = re.compile(r'(?:(\.)|(\.\d*?[1-9]\d*?))0+(?=\b|[^0-9])')

def remove_tail_dot_zeros(a):
    return tail_dot_rgx.sub(r'\2',a)

      

And now we can check this:

>>> remove_tail_dot_zeros('2.00')
'2'
>>> remove_tail_dot_zeros('200')
'200'
>>> remove_tail_dot_zeros('150')
'150'
>>> remove_tail_dot_zeros('2.59')
'2.59'
>>> remove_tail_dot_zeros('2.50')
'2.5'
>>> remove_tail_dot_zeros('2.500')
'2.5'
>>> remove_tail_dot_zeros('2.000')
'2'
>>> remove_tail_dot_zeros('2.0001')
'2.0001'
>>> remove_tail_dot_zeros('1500')
'1500'
>>> remove_tail_dot_zeros('1500.80')
'1500.8'
>>> remove_tail_dot_zeros('1000.50')
'1000.5'
>>> remove_tail_dot_zeros('200.50mt')
'200.5mt'
>>> remove_tail_dot_zeros('200.00mt')
'200mt'

      

+2


source


Look '.'

in the element and they decide to remove the trailing (right) null:



>>> nums = ['200', '150', '2.50', '1500', '1500.80', '100.50']
>>> for n in nums:
...     print n.rstrip('0').rstrip('.') if '.' in n else n
... 
200
150
2.5
1500
1500.8
100.5

      

+1


source


Try it,

import re

def strip(num):

    string = str(num)
    ext = ''

    if re.search('[a-zA-Z]+',string): 
        ext = str(num)[-2:]
        string = str(num).replace(ext, '')


    data = re.findall('\d+.\d+0$', string)
    if data:
        return data[0][:-1]+ext

    return string+ext

      

0


source







All Articles