在Python中删除小数点后的尾随零

时间:2017-05-22 10:59:44

标签: python string python-2.7 decimal-point

我正在使用Python 2.7。我需要在结尾处替换"0"字符串。

说,a =“2.50”:

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

我得到a = 2.5,我对这个结果很好。

现在a =“200”:

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

我得到a = 2,这个输出按照我同意的设计。但我希望输出a = 200。

实际上我正在寻找的是

  

当结尾的小数点后面的任何值为"0"时,替换"0"   没有价值。

以下是示例,我期待结果。

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

不是值是字符串。

注意:有时为a = 100LLa = 100.50mt

3 个答案:

答案 0 :(得分:3)

您可以使用正则表达式

执行此操作
import re

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

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

b是从a小数点后删除尾随零的结果。

我们可以用一个很好的函数来写这个:

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)

现在我们可以测试一下:

>>> 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'

答案 1 :(得分:1)

在项目中查找'.',他们决定删除尾随(右侧)零:

>>> 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

答案 2 :(得分:0)

试试这个,

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