Elliot Bonneville Elliot Bonneville - 1 year ago 180
Python Question

Math operations from string

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

), 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download