numeric expression from string?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Feb 4 09:51:52 EST 2006


On Sat, 04 Feb 2006 06:48:11 -0500, Brian Blais wrote:

> Hello,
> 
> I have a string input from the user, and want to parse it to a number, and would like 
> to know how to do it.  I would like to be able to accept arithmetic operations, like:
> 
> '5+5'
> '(4+3)*2'
> '5e3/10**3'
> 
> I thought of using eval, which will work, but could lead to bad security problems 
> (not that it's a big  deal in my app, but still...)

It is good to be cautious. Big thumbs up. But what exactly are you worried
about? Do you think your users might enter something Evil and break their
own system? I'd suggest that's not your problem, and besides, it is hard
to think of anything they could do with eval that they couldn't do by
exiting your app and running something Evil in their shell prompt.

Are you running this script as a cgi script? Then remote users might use
eval to break your system, and you are right to avoid it.

Are you worried about angry customers calling you up with bizarre bugs,
because they entered something weird into their input string? One
possible way to avoid those problems is to validate the string before
passing it to eval:

goodchars = "0123456789+-/*()eE."
for c in user_input:
    if c not in goodchars:
        raise ValueError("Illegal character detected!")
result = eval(user_input)



> string.atof won't do the job.  Is there a preferred way of doing this?

Look into PyParsing:

http://cheeseshop.python.org/pypi/pyparsing/1.3.3

If you read back over the Newsgroup archives, just in the last week or so,
there was a link to a PyParsing tutorial.


-- 
Steven.




More information about the Python-list mailing list