【问题标题】:How to remove leading zeros from the calculator expression in a string? python如何从字符串中的计算器表达式中删除前导零? Python
【发布时间】:2020-11-04 18:15:39
【问题描述】:

我有一个疑问,在 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"

如何解决

【问题讨论】:

  • 如果你有一个字符串列表,你可以使用''.join(strings)将它们组合成一个字符串。
  • @FrankYellin 但是操作数呢?
  • 你有什么问题?你拿起你的绳子,你把它分成几块,你剥掉每一块,然后你把它连接起来,然后作为一根绳子重新组合在一起。这不是你想要做的吗?
  • @FrankYellin 我的意思是我希望结果是“123+567*29/3-7”
  • 这不是你得到的吗?

标签: python string strsplit leading-zero


【解决方案1】:
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))

【讨论】:

  • 我们可以在res.append(int(Z[j:i]))中使用float而不是int,因为我们需要考虑十进制值@Andrey
  • @KaryKathews 是的,你是对的,如果数字可以是真实的,必须使用浮点数以免丢失小数部分。干得好!
【解决方案2】:
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

【讨论】:

  • 非常感谢@VinayKurmi
  • 我们需要删除十进制值
【解决方案3】:
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) 删除所有不必要的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))

自己尝试一下,如果它对你有用,请在 cmets 中告诉我!

【讨论】:

  • 还有一点,我们需要考虑十进制值
  • @KaryKathews : 谢谢我现在添加了对十进制支持的支持
  • 但如果我们使用“00123+0567*29/03-7+0-0”我得到“34-4+92.1+-”你能建议我们如何制作“ 34-4+92.1+0-0”? @Lakshya Raj
  • @KaryKathews:好的,我更新了我的代码以小心由零组成的数字!
【解决方案4】:

这是一个简洁的(如果你去掉代码中的所有注释)和优雅的方式来实现这一点:

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

【讨论】:

  • @KaryKathews 我已经解决了这个问题。你可以再试一次...
  • 但是有小数的值呢?
【解决方案5】:

可以用正则表达式来完成:

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)

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

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多