evaluating a string

Joal Heagney s713221 at student.gu.edu.au
Wed Oct 18 04:01:13 EDT 2000


Joal Heagney wrote:

> 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

Hmm. Well that was wierd. It kinda worked on something similar, but when I
tried it on the above string to check *shrugs*. This one works, but I don't
think it will work all the time:

>>> eval("1+2*3/4"".0")
Perhaps a regular expression???

Joal Heagney/AncientHart




More information about the Python-list mailing list