Evaluating strings as values

Is it possible in Python to calculate a member in a string? For example:

string_a = "4 ** (3 - 2)"

unknown_function(string_a) = 4

      

Is it possible? Is there a function that mimics "unknown_function" in my example?

+3


source to share


3 answers


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!

+5


source


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.

+8


source


Yes, you can use the function eval

.

>>> string_a = "4 ** (3 - 2)"
>>> eval(string_a)
4
>>> 

      

More details can be found in the documentation

+3


source







All Articles