簡體   English   中英

在Python中刪除小數點后的尾隨零

[英]Remove trailing zeros after the decimal point in Python

我使用的是Python 2.7。 我需要在結尾處替換"0"字符串。

比如,a =“2.50”:

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

我得到一個= 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

您可以使用正則表達式執行此操作:

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'

尋找'.' 在項目中他們決定刪除尾隨(右側)零:

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

試試這個,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM