Calculate a Python string

Asked

Viewed 1,416 times

0

I would like to make a calculation of a string that I receive, for example:

var = '1+2'

Wanted to turn this string into an account, to return 3 to the variable var and not '1+2', but this would not only be added, it would have subtraction, multiplication and division, it could still have a mixed operation, ex: var = '2*4+1' and so on... I think you’ve understood...

The problem is that I get this account as string

I tried to use the int(var), but it certainly wouldn’t have some function like calc(var)?

  • I believe that what you need is to interpret and process a mathematical expression contained within a string, I found an answer to what you need in this link I hope I helped. Hugs.

1 answer

3


Assuming you will be careful with the inputs you receive the simplest way is:

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

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

As @jsbueno said well, you can use Ast.literal_eval, which is safer if you don’t have control over the inputs that enter the function eval():

import ast
print(ast.literal_eval('4+10')) # 14
  • 1

    There is the option of ast.literal_eval which only allows the anification of primitive Python types, without executing arbitrary code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.