Turning a string into an programatic mathematical expression

Steve Holden steve at holdenweb.com
Tue Oct 19 22:50:58 EDT 2004


Daniel Bickett wrote:

> The title really says it all. I'm trying to take input from a user
> (intended to be a mathematical expression), from a text box for
> example, and evaluate it mathematically within the program. For
> clarification: the user inputs the string "4*5(3-3)", I would be
> interested in a straight-forward way to find the result of that, based
> only on a string. The follow-up question would be how to incorporate
> variables into the mix, however I'll leave it at that for now. Thanks
> for your time :)
> 
> Daniel Bickett

I should, perhaps, have explained that the input() built-in essentially 
applies the eval() function to an input string. So, whatever the source 
of your string you can use eval() to evaluate it.

The difficulty is that there's little control over what the user can 
enter (though you do get the choice of providing dictionaries of local 
and global variables it's hard to limit what users have access to and 
still provide sufficient functionality).

 >>> eval('"Hello" + " " + "world"')
'Hello world'
 >>> eval("3+14/27.4")
3.5109489051094891
 >>>

regards
  Steve
-- 
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119



More information about the Python-list mailing list