How to split algebraic expressions in a string using python?

You could re.findall all groups of characters followed by + or - (or end-of-string $), then strip the + (which, like -, is still part of the following group) from the substrings.

>>> s = "-9x+5x-2-4x+5"
>>> [x.strip("+") for x in re.findall(r".+?(?=[+-]|$)", s)]
['-9x', '5x', '-2', '-4x', '5']

Similarly, for the second string with =, add that to the character group and also strip it off the substrings:

>>> s = '-3x-5x+2=9x-9'
>>> [x.strip("+=") for x in re.findall(r".+?(?=[+=-]|$)", s)]
>>> ['-3x', '-5x', '2', '9x', '-9']

Or apply the original comprehension to the substrings after splitting by =, depending on how the result should look like:

>>> [[x.strip("+") for x in re.findall(r".+?(?=[+-]|$)", s2)] for s2 in s.split("=")]
>>> [['-3x', '-5x', '2'], ['9x', '-9']]

In fact, now that I think of it, you can also just findall that match an optional minus, followed by some digits, and an optional x, with or without splitting by = first:

>>> [re.findall(r"-?\d+x?", s2) for s2 in s.split("=")]
[['-3x', '-5x', '2'], ['9x', '-9']]

One of many possible ways:

import re

term = "-9x+5x-2-4x+5"

rx = re.compile(r'-?\d+[a-z]?')
factors = rx.findall(term)
print(factors)

This yields

['-9x', '5x', '-2', '-4x', '5']

Tags:

Python

Regex