您的标题建议使用正则表达式,您自己的解决方案使用string.split(),这也是您得到相同字符串的原因:
expr = '1234 + 896 - 1207 + 1567 - 345'
words = word.split('-\|+') # splits only if ALL given characters are there
print(words)
固定(但不是你想要的):
expr = '1234 -\|+ 896 -\|+ 1207 -\|+ 1567 -\|+ 345'
words = expr.split('-\|+')
print(words)
输出:
['1234 ', ' 896 ', ' 1207 ', ' 1567 ', ' 345']
这是一个不使用正则表达式的替代解决方案:
遍历字符串中的所有字符,如果它是一个数字(没有空格也没有 +-),则将其添加到临时列表中。如果是 + 或 - 加入临时列表中的所有数字并将其添加到结果列表中:
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