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

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

"Fredrik Lundh" <fredrik at> wrote in message
news:FslN5.3921$QH2.398035 at
> 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


More information about the Python-list mailing list