### 基于正则表达式的字符串拆分

``````expr = '1234 + 896 - 1207 + 1567 - 345'
words = word.split('-\|+')
print(words)
``````

#### 3 个答案:

``````import re

word = '1234 + 896 - 1207 + 1567 - 345'
words = re.split(r' - | \+ ', word)
print(words)

# ['1234 ', '896', '1207', '1567', '345']
``````

``````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
``````

``````re.split(r"\s*([+-])\s*",expr)
Out: ['1234', '+', '896', '-', '1207', '+', '1567', '-', '345']
``````