Search code examples
pythonregexlistarithmetic-expressions

Regex Split string of arithmetic expression into list with its operators and numbers (decimal included)


I have made this code, but i don't think it's the best way.

import re
notation = "41*(5.5+6-(8/2^3)-7)-1"
n2 = [x[0] for x in re.findall(r"(\d+(\.\d+)?)",notation)]
n2.reverse()
m = []
x = True

for z in notation:
    if z.isdigit() and x:
        m.append(n2.pop())
        x = False
    if not z.isdigit() and z != ".": 
        m.append(z)
        x = True

The expected output is:

m = ['41', '*', '(', '5.5', '+', '6', '-', '(', '8', '/', '2', '^', '3', ')', '-', '7', ')', '-', '1']

I think this code has a kind of hardcoding, my doubt is how would you make it in a better way?


Solution

  • using regex findall, you can get your desired result!

    Regex:

    re.findall('[0-9.]+|.',m)
    

    therefore,

    >>> import re
    >>> notation  = '41*(5.5+6-(8/2^3)-7)-1'
    >>> m = re.findall('[0-9.]+|.',notation )
    >>> print m
    ['41', '*', '(', '5.5', '+', '6', '-', '(', '8', '/', '2', '^', '3', ')', '-', '7', ')', '-', '1']
    

    If you are specific about your symbols +\-*^/() then you can use

    >>> m = re.findall('[0-9.]+|[+\-*^/()]',notation)
    >>> print m
    ['41', '*', '(', '5.5', '+', '6', '-', '(', '8', '/', '2', '^', '3', ')', '-', '7', ')', '-', '1']
    

    will give you the desired result!

    Hope it helps!