evaluating a string

Joal Heagney s713221 at student.gu.edu.au
Wed Oct 18 03:54:41 EDT 2000


Matthew Dixon Cowles wrote:

> On Tue, 17 Oct 2000 04:01:24 GMT, prakash.ojha at hope.edu
> <prakash.ojha at hope.edu> wrote:
>
> >I am new to Python and would like to know how can I evaluate a string
> >like "1+2*3/4" to give a numeric result. Is there any built in
> >function that will give me this result. Any help would be greatly
> >appreciated.
>
> Since this is Python, the answer won't surprise you: the builtin
> eval() will do what you want:
>
> >>> eval("1+2*3/4")
> 2
>
> Anticipating what may be your next question, the reason that it
> doesn't give you 2.5 is that in Python, division of integers produces
> an integer result.
>
> Regards,
> Matt

And the quick way to get around that problem *showing of here*:

>>> eval("%s""1+2*3/4" 1.0)

*grins*

Joal Heagney/AncientHart




More information about the Python-list mailing list