Splitting a math expression string into tokens in Python

You should split on the character set [+-/*] after removing the whitespace from the string:

>>> import re
>>> def mysplit(mystr):
...     return re.split("([+-/*])", mystr.replace(" ", ""))
...
>>> mysplit("A7*4")
['A7', '*', '4']
>>> mysplit("Z3+8")
['Z3', '+', '8']
>>> mysplit("B6 / 11")
['B6', "https://stackoverflow.com/", '11']
>>>

Leave a Comment