srtring to int question
Bernhard Herzog
herzog at online.de
Sun Aug 13 06:16:54 EDT 2000
"Darrell Gallion" <darrell at dorb.com> writes:
> Dooo@!
> Those examples make more sense like this.
> The re prevents bad things from being input into eval.
>
> def convert(s):
> try:
> x = int(s)
> except:
> print "Not a number"
> return None
> return x
>
> def convert(s):
> try:
> assert(re.match("\s*\d+",s))
Using assert for this is a bad idea. Assert statements will be omitted
if the code is optimized (Python's -O option). They're meant to check
internal program state and invariants, not to validate user input.
The regex used has a bug, btw. It doesn't allow signs, e.g. "-1" will
not be matched.
> x=eval(s,{},{})
> except:
> print "Not a number"
> return None
> return x
--
Bernhard Herzog | Sketch, a drawing program for Unix
herzog at online.de | http://sketch.sourceforge.net/
More information about the Python-list
mailing list