Let's say I have a standard Python string (such as one obtained from
Use the eval function.
print eval('2 + 4')
You can even use variables or regular python code.
a = 5 print eval('a + 4')
You also can get return values:
d = eval('4 + 5') print d
Or call functions:
def add(a, b): return a + b def subtract(a, b): return a - b a = 20 b = 10 print eval('add(a, b)') print eval('subtract(a, b)')
In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.
On the other hand, as others have mentioned, eval is not safe so use it wisely.