ops = set( "+-" )
expr = '1234 + 896 - 1207 / 1567 - 345'
# result list
numbers = []
# temporary list
num = []
for c in expr:
if c in ops:
numbers.append( ''.join(num))
numbers.append( c ) # comment this line if you want to loose operators
num = []
elif c != " ":
num.append(c)
if num:
numbers.append( ''.join(num))
print(numbers)
输出:
['1234', '+', '896', '-', '1207/1567', '-', '345']
['1234', '896', '1207', '1567', '345'] # without numbers.append( c ) for c in ops
您的标题建议使用regex,您自己的解决方案使用string.split(),这也是您获得相同字符串的原因:
修正(但不是你想要的):
输出:
下面是一个不使用regex的替代解决方案:
迭代字符串中的所有字符,如果它是一个数字(没有空格和+-),则将其添加到临时列表中。如果是+或-连接临时列表中的所有数字并将其添加到结果列表:
输出:
如果要保留运算符,请使用组括号:
使用
re.split
拆分多个分隔符:相关问题 更多 >
编程相关推荐