Getting row result?

Well, let them say that I have the string s = '5 + 7'

Is it possible to get the result of this line? (It should be 12)

I tried using int(s) , but this will give an error

0
source share
2 answers

You are looking for eval:

 >>> s = '5 + 7' >>> eval(s) 12 

Be careful not to run it on untrusted code, since an attacker can use it to run arbitrary code on your system. For example, if the user can make s equal to "__import__('os').execve('/bin/sh',[],{})" , then eval(s) will provide the user with a shell on your computer.

+5
source

A safe way to do this (instead of the eval() function) is to use the ast library:

 import ast ast.literal_eval('5 + 7') # -> 12 
+2
source

Source: https://habr.com/ru/post/1259709/


All Articles