How do I convert arithemtic string (like "2+2") to a number?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sun Feb 6 05:15:52 EST 2005


Michael Hartl wrote:
> Adam brings up a good point: eval is a very general function which
> evaluates an arbitrary Python expression.  As a result, it (and its
> close cousin exec) should be used with caution if security is an issue.

To get a secure eval for simple mathematical expressions, it should
suffice to check the string in the following way:

It does not contain characters other than operators, numbers, dots and
parentheses (perhaps you want to allow 'e' for floats, but you should
make sure that the 'e' is surrounded by numbers or optionally followed
by a +/- sign).

If you want to go a step further, you could parse the string to eval
with the parser/tokenize/... modules and verify the parse tree that it
contains nothing except operators and numbers.

Reinhold



More information about the Python-list mailing list