String split based on regular expressions in python

3290 views python
-3

I have the mathematical expression in string format. Which contains only '+' or '-' operators. I have to split the string on the basis of operators.

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

I have tried this but it gives original string as it is.

answered question

1 Answer

0

Use re.split to split on multiple delimiters:

import re

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

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

posted this

Have an answer?

JD

Please login first before posting an answer.