如何从字符串中的计算器表达式中删除前导零? 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) 试过 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

这里有一个简洁的(如果你去掉代码中的所有注释)并且优雅的实现方式:

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 从每个操作数中分离出零。在此之后 在运算符列表的末尾添加一个额外的空运算符 。然后将每个操作数与相应的运算符连接起来(空运算符与最后一个操作数连接起来)。最后加入列表,获得最终表情

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,'listify'它,并将pos设置到Z中的最后一个位置。然后它使用循环和 Z = "".join(Z) 删除所有不必要的 0s。然后它 prints 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"
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"",Z)
#substitute start of string, leading zeroes, digits with digits
sub2=re.sub(r2,r"",sub1)
print(sub2)

分两次完成(处理字符串开头的前导零),我不知道是否可以一次完成。