[Tutor] Evaluating a string expression

Alan Gauld alan.gauld at btinternet.com
Fri Nov 6 09:34:33 CET 2009


"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?

If your string forms a well defined pattern you can parse the string into
its components - an arithmetic calculation in the example and execute it 
that way.
There are Python modules/tools available to help create such parsers and if
you are dealing with well defined input that is probably the safest 
approach.

Use eval() only if you know that the input cannot be malicious (or 
accidentally bad)
code.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list