The easiest way is to use eval
as in:
>>> eval("2 + 2")
4
Pay attention to the fact I included spaces in the string. eval
will execute a string as if it was a Python code, so if you want the input to be in a syntax other than Python, you should parse the string yourself and calculate, for example eval("2x7")
would not give you 14 because Python uses *
for multiplication operator rather than x
.