Calculating strings as values
Question: Is it possible in Python to calculate a term in a string? For example:

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

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

Thanks!


Answer: Just like `sympy` was a useful module for your [last
question](http://stackoverflow.com/questions/14668495/mathematical-function-
unassigned-variables), it can apply 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 though that this will return `sympy` objects, and if you want to get an
integer or a float out of it you should do the conversion explicitly:

    
    
    >>> type(sympy.sympify("4**(3-2)"))
    <class 'sympy.core.numbers.Integer'>
    >>> int(sympy.sympify("4**(3-2)"))
    4
    

I hacked together a recipe to turn string expressions into functions
[here](http://stackoverflow.com/a/13734176/487339) which is kind of cute.

