本文介绍了在 Python 中删除尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到一种在python中转换以下字符串的方法:
I need to find a way to convert the following strings in python:
0.000 => 0
0 => 0
123.45000 => 123.45
0000 => 0
123.4506780 => 123.450678
等等.我试过 .rstrip('0').rstrip('.'),但如果输入是 0 或 00,那这不起作用.
and so forth. I tried .rstrip('0').rstrip('.'), but that doesn't work if the input is 0 or 00.
有什么想法吗?谢谢!
推荐答案
更新 通用化以保持精度和处理看不见的值:
Updated Generalized to maintain precision and handle unseen values:
import decimal
import random
def format_number(num):
try:
dec = decimal.Decimal(num)
except:
return 'bad'
tup = dec.as_tuple()
delta = len(tup.digits) + tup.exponent
digits = ''.join(str(d) for d in tup.digits)
if delta <= 0:
zeros = abs(tup.exponent) - len(tup.digits)
val = '0.' + ('0'*zeros) + digits
else:
val = digits[:delta] + ('0'*tup.exponent) + '.' + digits[delta:]
val = val.rstrip('0')
if val[-1] == '.':
val = val[:-1]
if tup.sign:
return '-' + val
return val
# test data
NUMS = '''
0.0000 0
0 0
123.45000 123.45
0000 0
123.4506780 123.450678
0.1 0.1
0.001 0.001
0.005000 0.005
.1234 0.1234
1.23e1 12.3
-123.456 -123.456
4.98e10 49800000000
4.9815135 4.9815135
4e30 4000000000000000000000000000000
-0.0000000000004 -0.0000000000004
-.4e-12 -0.0000000000004
-0.11112 -0.11112
1.3.4.5 bad
-1.2.3 bad
'''
for num, exp in [s.split() for s in NUMS.split('\n') if s]:
res = format_number(num)
print res
assert exp == res
输出:
0
0
123.45
0
123.450678
0.1
0.001
0.005
0.1234
12.3
-123.456
49800000000
4.9815135
4000000000000000000000000000000
-0.0000000000004
-0.0000000000004
-0.11112
bad
bad
这篇关于在 Python 中删除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!