[Tutor] Evaluating a string expression

Kent Johnson kent37 at tds.net
Fri Nov 6 16:53:31 CET 2009


On Fri, Nov 6, 2009 at 3:34 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Modulok" <modulok at gmail.com> wrote
>
>>> I would like to know how would I evaluate a string expression in python.
>>> For example, if i say:
>>>>>>
>>>>>> a = "3*2"
>>>
>>> I want to do something to evaluate the variable 'a' to give me 6. How
>>> can I do this?
>>
>> [/snip]
>>
>> The eval() function can do this:
>>
>>  eval("3*2")
>>
>> WARNING: Long winded security rant below...
>
> And these are valid warnings which begs the question what are the
> alternatives?

Python 2.6 includes the ast.literal_eval() function which will
evaluate literal expressions:
http://docs.python.org/library/ast.html#ast.literal_eval

This is a bit too limited for the OP however.

The Python Cookbook has several examples of safe eval functions that
work by parsing an expression and evaluating the parse tree, only
allowing specific types of nodes. For example this one which does
allow arithmetic expressions:
http://code.activestate.com/recipes/286134/

Kent


More information about the Tutor mailing list