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

Gaute B Strokkenes gs234 at cam.ac.uk
Mon Nov 6 05:36:11 EST 2000


"Alex Martelli" <aleaxit at yahoo.com> writes:

> 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.
> 
> To check for '1 or more digits', just change the
> regular expression rawstring to r'\d+'.

I did this, but it doesn't work properly.  It returns 1 no matter
what.

After looking at the docs for a while, I came up with the following:

def isanum(str):
    import re
    return re.match(r'^[0-9]', str) != None

Which works beautifully.

Thanks to everyone who gently pushed me in the right direction.

-- 
Big Gaute                               http://www.srcf.ucam.org/~gs234/
I hope I bought the right relish...  zzzzzzzzz...



More information about the Python-list mailing list