修剪任意数量的零

时间:2017-08-24 22:32:52

标签: python

我有一个函数可以从整数中修剪尾随小数位并将其转换为字符串。例如,trim(1.0)输出'1'。

这是我的代码:

def trim(num): 
     num1 = str(num) 
     try: 
         if '.0' in num1: 
             return num1[:num1:rfind('.0')]
         return num1
     except Exception: 
         pass

虽然这会完美地处理带有1个尾随小数位的数字,但它不适用于更多的小数位(例如2.000)。有没有办法修剪所有尾随小数位?

1 个答案:

答案 0 :(得分:1)

首先,您的代码有问题。如果我拿走你的代码并运行它:

print(your_trim(1.1))  
print(your_trim(1.0566))
print(your_trim('1cm'))

输出结果为:

1.1  
1    <-- this is dangerous, the value is 1.0566!
1cm  <-- this is not even a number

正如评论者所提到的,你可能会错误的浮点数和整数。顾名思义,integer没有小数位。如果您的目标是删除尾随零(无论出于何种原因)并且float围绕到int,您可以使用类似这样的方法:

def strip_trailing_zeroes(num):
     if isinstance(num, float):
         if int(num) == num:
             return int(num)
         else:
             return num
     else:
         raise ValueError("Parameter is not a float")

测试代码:

print(strip_trailing_zeroes(1.1))
print(strip_trailing_zeroes(1.0566))
print(strip_trailing_zeroes(1.000))
print(strip_trailing_zeroes('1cm'))

返回输出:

1.1
1.0566
1
Exception with "ValueError: Parameter is not a float"

正如其他评论者所说,我无法想象一个用例。

可能会追求的是从&#34;字符串表示中删除尾随零&#34;一个浮子。为此,简单的正则表达式替换就足够了:

# match a decimal point, followed by one or more zeros
# followed by the end of the input
print(re.sub('\.0+$', '', '2.000'))