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

<p>For examples :</p>

<p>Input 1 : <code>"2*4^7"</code></p>

<p>Output 1 : <code>"(2*(4^7))"</code></p>

<p>Input 2 : <code>"sin(x)*3-8^9"</code></p>

<p>Output 2 : <code>"((sin(x)*3)-(8^9))"</code></p>

<p>Input 3 : <code>"(2-8)/6"</code></p>

<p>Output 3 : <code>"((2-8)/6)"</code></p>

<p>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. </p>

<p>I'm working with python 3</p>

<p>Thank you!</p>

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

<pre><code>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(
                represent(tree.left),
                op,
                represent(tree.right),
                )
    elif t == ast.Num:
        return str(tree.n)
    elif t == ast.Name:
        return tree.id
    elif t == ast.Call:
        return "{}({})".format(
                represent(tree.func),
                represent(tree.args),
                )
    ...

# prints (((sin(x)*2)*x)+4)
print(represent(ast.parse("sin(x)*2*x+4")))
</code></pre>

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

python string python-3.x