srtring to int question

Donald O'Donnell donod at home.com
Mon Aug 14 21:24:55 EDT 2000


Bernhard Herzog wrote:

<cut>
> 
> 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
> 
> --
Not only that, but it will match on 1 or more digits followed by
anything...

	re.match("\s*\d+", "  23skidoo")

will return a valid match object.  What you want is:

	re.match("\s*[+-]?\d+\s*$", s)

This will allow a +/- prefix and trailing spaces as well.

But I agree, try/except is a better way to handle this case.


Don O'Donnell



More information about the Python-list mailing list