簡體   English   中英

如何從字符串中的計算器表達式中刪除前導零? Python

[英]How to remove leading zeros from the calculator expression in a string? python

我有一個疑問,在 python 中,字符串是, Z = "00123+0567*29/03-7"

如何將其轉換為“123+567*29/3-7”

即使我re.split('[+]|[*]|-|/', Z)嘗試使用re.split('[+]|[*]|-|/', Z)使用for i in res : i = i.lstrip("0")但它會正確拆分,但要加入返回與字符串“Z”相同的操作數作為Z = "123+567*29/3-7"

如何解決

def cut_zeroes(Z):
    i, res = 0, []
    n = len(Z)

    while i < n:
        j = i
        while i < n and Z[i] not in '+-/*':
            i += 1
        res.append(int(Z[j:i]))

        if i < n:
            res.append(Z[i])

        i += 1

    return ''.join(map(str,res))
  

Z = "00123+0567*29/03-700"
print(cut_zeroes(Z))
Z = "00123+0567*29/03-7"
print Z

import re
res = re.split(r'(\D)', Z)
print res

empty_lst = []
for i in res :
    i = i.lstrip("0")
    empty_lst.append(i)
    print i
print empty_lst
new_str = ''.join(empty_lst)
print new_str
def zero_simplify(Z):
    from re import sub
    return [char for char in sub("0{2,}", "0", Z)]

Z = "00123+0567*29/03-7+0-000"
Z = zero_simplify(Z)
pos = len(Z)-1
while pos>-1:
    if Z[pos]=="0":
        end = pos
        while Z[pos] == "0":
            pos-=1
            if pos==-1:
                del Z[pos+1:end+1]
        if (not Z[pos].isdigit()) and (Z[pos] != ".") and (Z[pos] == "0"):
            del Z[pos+1:end+1]
    else:
        pos-=1
Z = "".join(Z)
print(Z)

這樣做是設置Z ,“列出”它,並將pos設置為Z的最后一個位置。 然后它使用循環和Z = "".join(Z)刪除所有不必要的0 s。 然后它在最后print s Z 如果你想要一個函數來刪除零,你可以這樣:

def zero_simplify(Z):
    from re import sub
    return [char for char in sub("0{2,}", "0", Z)]

def remove_unnecessary_zeroes(Z):
    Z = [char for char in Z]
    pos = len(Z)-1
    while pos>-1:
        if Z[pos]=="0":
            end = pos
            while Z[pos] == "0":
                pos-=1
                if pos==-1:
                    del Z[pos+1:end+1]
            if (not Z[pos].isdigit()) and (Z[pos] != ".") and (Z[pos] == "0"):
                del Z[pos+1:end+1]
        else:
            pos-=1
    Z = "".join(Z)
    return Z
Z = "00123+0567*29/03-7+0-000"
print(remove_unnecessary_zeroes(Z))

自己嘗試一下,並在評論中告訴我它是否適合您!

這是一個簡潔的(如果你去掉代碼中的所有注釋)和優雅的方式來實現這一點:

import re

Z = "00123+0567*29/03-7"

operators = re.findall('\D', Z)               # List all the operators used in the string
nums = re.split('\D', Z)                      # List all the numbers in the list

operators.append('')                          # Add an empty operator at the end
nums = [num.lstrip('0') for num in nums]      # Strip all the leading zeroes from each numbers

# Create a list with the operands (numbers) concatenated by operators

num_operator_list = [nums[i] + operators[i] for i in range(len(nums))]

# Join all the intermediate expressions to create a final expression

final_expression = ''.join(num_operator_list)
print(final_expression)

輸出

123+567*29/3-7

解釋

首先,您需要將運算符和操作數分開,然后從每個操作數中lstrip零。 在此之后,在操作符列表的末尾添加一個額外的空操作符。 然后將每個操作數與相應的運算符連接起來(空運算符與最后一個操作數連接)。 最后,加入列表以獲得最終表達式。

它可以用正則表達式完成:

import re
Z = "00123+0567*29/03-7"
r1=r"(\D)0+(\d+)"
r2=r"\b0+(\d+)"
#substitute non-digit,leading zeroes, digits with non-digit and digits
sub1=re.sub(r1,r"\1\2",Z)
#substitute start of string, leading zeroes, digits with digits
sub2=re.sub(r2,r"\1",sub1)
print(sub2)

它分兩次完成(處理字符串開頭的前導零),我不知道是否可以一次完成。

暫無
暫無

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

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