Elliot Bonneville Elliot Bonneville - 4 months ago 18
Python Question

Math operations from string

Let's say I have a standard Python string (such as one obtained from

raw_input()
), maybe "2 + 2" for simplicity's sake. I'd like to convert this string to standard math operations in Python, such that "2 + 2" would return 4. Is there an easy way to do this, or would I have to split on the spaces and parse each number/symbol manually, then do the math based on what I find? Do I want Regex?

Answer

Use the eval function.

print eval('2 + 4')

Output:

6

You can even use variables or regular python code.

a = 5
print eval('a + 4')

Output:

9

You also can get return values:

d = eval('4 + 5')
print d

Output:

9

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)')

Output:

30
10

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.