编程语言
首页 > 编程语言> > 在Python中删除小数点后的尾随零

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

作者:互联网

我正在使用Python 2.7.我需要在结尾处替换“ 0”字符串.

假设a =“ 2.50”:

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

我得到= 2.5,这个结果我很好.

现在a =“ 200”:

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

我得到a = 2,并且此输出是按照我同意的设计进行的.但是我希望输出a = 200.

其实我在找

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

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

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 = 100LL或a = 100.50mt.

解决方法:

您可以使用正则表达式执行此操作:

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'

标签:decimal-point,python-2-7,string,python
来源: https://codeday.me/bug/20191026/1932873.html