4

I am using Python 2.7. I need to replace "0" string at the end.

Say, a = "2.50":

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

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

Now a = "200":

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

I get a = 2, and this output is as per design I agreed. But I expect the output a = 200.

Actually what I am looking is

when any value after decimal point at the end is "0" replace that "0" with None value.

Below are the examples and I am expecting 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 string.

Note: sometimes a = 100LL or a = 100.50mt.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kitty
  • 105
  • 1
  • 3
  • 16

3 Answers3

5

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 tailing 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 test 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'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

Look for '.' in the item and them decide to remove the trailing (right-side) zero:

>>> 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
Nabeel Ahmed
  • 18,328
  • 4
  • 58
  • 63
  • sorry I did not update in question now i Have updated. it wont work when value is 250.50mt i need it as 250.5mt – kitty May 22 '17 at 12:19
0

Try this,

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
Muthuraj S
  • 107
  • 6