我有一个疑问,在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"
相同的操作数连接。
如何解决这个问题
发布于 2020-11-04 18:34:06
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))
发布于 2020-11-04 18:34:56
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
发布于 2020-11-04 18:50:13
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‘it,并将pos
设置为Z
中的最后一个位置。然后,它使用循环和0
删除所有不必要的Z = "".join(Z)
。最后是print
的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))
自己试一试,在评论中告诉我它是否对你有用!
https://stackoverflow.com/questions/64685578
复制相似问题