Evaluating strings as values
Exist eval
eval(string_a)
# 4
But don't use this under any circumstances if it string_a
comes from someone other than you, because they can easily hack into your systems and destroy your files!
source to share
Just as sympy
was a helpful module for your last question , it can be applied here:
>>> import sympy
>>> sympy.sympify("4**(3-2)")
4
and even
>>> sympy.sympify("2*x+y")
2*x + y
>>> sympy.sympify("2*x+y").subs(dict(x=2, y=3))
7
Note that this will return objects sympy
, and if you want to get an integer or float from it, you have to do the conversion explicitly:
>>> type(sympy.sympify("4**(3-2)"))
<class 'sympy.core.numbers.Integer'>
>>> int(sympy.sympify("4**(3-2)"))
4
I hacked a recipe to turn string expressions into functions here , which is pretty cute.
source to share
Yes, you can use the function eval
.
>>> string_a = "4 ** (3 - 2)"
>>> eval(string_a)
4
>>>
More details can be found in the documentation
source to share