Search code examples
python-3.xregexstringevalpython-re

Evaluate expression in a string in python


I have a string with mathematical operations, how do I evaluate the string within [] to generate the output shown below?

mystring = "[2*3-1] plus [4+2] is equal to [5+6]."

re.findall(r"\[(.*?)\]",mystring) # to find 2*3-1, 4+2, 5+6

Output: "5 plus 6 is equal to 11." # expected output. 

Solution

  • You may use re.sub with eval and a callback function here:

    mystring = "[2*3-1] plus [4+2] is equal to [5+6]."
    output = re.sub(r'\[(.*?)\]', lambda m: str(eval(m.group(1))), mystring)
    print(output)  # 5 plus 6 is equal to 11.
    

    The strategy here is to match the aritrmetic expression inside every [...], which then gets passed to a lambda function. There, we call eval() to get the result, cast to a string and generate the replacement.