evaluating a string

Joal Heagney s713221 at student.gu.edu.au
Wed Oct 18 15:33:39 EDT 2000


piet at cs.uu.nl wrote:

> >>>>> Joal Heagney <s713221 at student.gu.edu.au> (JH) writes:
>
> JH> Okay, sorry about that. How embarassing. Perhaps I should code before opening
> JH> my mouth, huh? Anycase, here is a baby implementation of a string evaluator
> JH> that doesn't get hung up on integer division.
>
> >>>> def string_eval(text):
> JH> ...     splittext = re.split("/", text)
> JH> ...     text2 = ""
> JH> ...     for i in range(len(splittext)-1):
> JH> ...             text2 = text2 + splittext[i] + ".0/"
> JH> ...     text2 = text2 + splittext[-1]
> JH> ...     return eval(text2)
> JH> ...
> >>>> string_eval("1+2*3/4")
> JH> 2.5
> >>>>
>
> If you want to have fractional answers then you should also accept
> fractional input. So what about
> "1+2*3.6/4"
> --
> Piet van Oostrum <piet at cs.uu.nl>
> URL: http://www.cs.uu.nl/~piet [PGP]
> Private email: P.van.Oostrum at hccnet.nl

Yikes. *grins* How about
>>> import re
>>> def string_eval(text):
...     splittext = re.split("/", text)
...     text2 =""
...     for i in range(len(splittext) - 1):
...             text2 = text2 + splittext[i] + "* 1.0/"
...     text2 = text2 + splittext[-1]
...     return eval(text2)
...
>>> string_eval("1+2*3/4")
2.5
>>> string_eval("1+2*3.6/4")
2.8

Joal Heagney/AncientHart




More information about the Python-list mailing list