Olivier Olivier - 26 days ago 11
Python Question

Convert string expression to mathematical expression?

I'm looking for something that would take a mathematical expression string as an input and would change it by adding parentheses to it.

For examples :

Input 1 :


Output 1 :

Input 2 :

Output 2 :

Input 3 :

Output 3 :

I'm currently trying to code it, but it's taking too much time and I would rather focus on other things, so if you guys know some module that could do that, that would be great.

I'm working with python 3

Thank you!


Using the ast module, you can parse your string and then traverse it to build a string representation you require:

import ast

def represent(tree):
    t = type(tree)
    if t == ast.Module:
        return represent(tree.body)
    elif t == list:
        # arithmetic expression should only be one thing
        return ", ".join(represent(part) for part in tree)
    elif t == ast.Expr:
        return represent(tree.value)
    elif t == ast.BinOp:
        o = type(tree.op)
        if o == ast.BitXor:
            op = "^"
        elif o == ast.Mult:
            op = "*"
        elif o == ast.Add:
            op = "+"
        return "({}{}{})".format(
    elif t == ast.Num:
        return str(tree.n)
    elif t == ast.Name:
        return tree.id
    elif t == ast.Call:
        return "{}({})".format(

# prints (((sin(x)*2)*x)+4)

As @user2357112 noted in the comments, this will only work if you limit yourself to use Python's expression syntax, most importantly by using ** instead of ^ for exponentiation.