How can I tell when a string is in fact a number?

Alex Martelli aleaxit at yahoo.com
Mon Nov 6 11:46:40 CET 2000


"Fredrik Lundh" <fredrik at effbot.org> wrote in message
news:FslN5.3921$QH2.398035 at newsb.telia.net...
> Alex Martelli wrote:
> > The simplest way to check if a string is made up
> > just of digits is probably via the re module...:
> >
> > def isanum(str):
> >     import re
> >     return re.match(r'\d*',str)!=None
> >
> > this checks for '0 or more digits', like your original
> > code -- i.e., an empty str will get a 1 return value.
>
> and so will anything else that starts with zero
> or more digits:

Whoops, thanks for pointing out the error -- it's
of course a silly typo (missing $ at the end of the
regular-expression rawstring), and the fix is:

def isanum(str):
    import re
    return re.match(r'\d*$',str)!=None


Alex






More information about the Python-list mailing list