evaluating a string

piet at cs.uu.nl piet at cs.uu.nl
Wed Oct 18 11:43:51 EDT 2000


>>>>> 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



More information about the Python-list mailing list