Language change and code breaks

Bjorn Pettersen BPettersen at NAREX.com
Thu Jul 12 11:06:16 EDT 2001


> From: "Jürgen A. Erhard" [mailto:juergen.erhard at gmx.net]

[snip]

> I had a script recently where I wanted to pass in a command line param
> that could be a numeric ratio, s.th. like
> 
>    thescript --ratio=1/3
> 
> Now, what do I do with that?  I can't use 1/3, because that eval'd is
> 0.  So... either people need to specify a float (--ratio=.3333... not
> very good looking) or I have to do some magic inside the script (look
> whether the ratio contains a /, split, float() on part, and merge)

If you're eval'ing random strings the user types in you really deserve
whatever you get <1/3 wink>.

>>> r = '1/3'
>>> import re
>>> tmp = r.split('/')
>>> assert len(tmp) == 2
>>> a, b = tmp
>>> assert re.match(r'[0-9]+', a) != None
>>> assert re.match(r'[0-9]+', b) != None
>>> x, y = map(int, [a,b])
>>> ratio = (x + 0.0) / y
>>> ratio
0.33333333333333331
>>>

Nothing magic about it...

-- bjorn




More information about the Python-list mailing list