Calculate a string in Python

0

I would like to do a calculation of a string that I get, for example:

var = '1+2'

I wanted to convert this string into an account, to return 3 for the variable var and not '1 + 2', but this would not only be added, would have subtraction, multiplication and division, may still have a mixed operation, ex : var = '2*4+1' and etc ... I think you already understand ...

The problem is that I get this account as string

I tried to use int(var) , but not sure would have some function type calc(var) ?

    
asked by anonymous 16.03.2017 / 15:50

1 answer

3

Assuming you're going to be careful about the inputs you get the simplest way is:

var = '1+2'
print(eval(var)) # 3

var = '5*3'
print(eval(var)) # 15

As the cologa @jsbueno said well, you can use ast.literal_eval, which turns out to be safer if you do not have control over the inputs that enter into the eval() function:

import ast
print(ast.literal_eval('4+10')) # 14
    
16.03.2017 / 15:58