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

Alex Martelli aleaxit at yahoo.com
Mon Nov 6 08:04:19 EST 2000


"Gaute B Strokkenes" <gs234 at cam.ac.uk> wrote in message
news:4aem0pe3rn.fsf at kern.srcf.societies.cam.ac.uk...
> Gaute B Strokkenes <gs234 at cam.ac.uk> writes:
>
> > 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.
>
> Whoopsie.  What I meant was:
>
> def isanum(str):
>     import re
>     return re.search(r'[^0-9]', str) == None

Heh -- it's easy to make typos, isn't it?  I made one myself,
which is why my original RE didn't work (forgot the $ at the
end).

The following presentation of the two RE-based solutions
may prove more readable, I think -- and it will be faster
unless the re.xx calls happen to be able to compile and
cache the RE's being used (compiling explicitly is, I think,
preferable -- 'explicit is better than implicit'...):


import re

all_digits=re.compile(r'\d*$')
any_non_digit=re.compile(r'[^0-9]')

def isanum1(str):
    return all_digits.match(str) != None

def isanum2(str):
    return any_non_digit.search(str) == None


I tried to see if either approach would exhibit substantially
better performance, but, no -- at least on my machine, they're
taking the same time to within measurement error (about 70
milliseconds for a thousand checks of an 80-character string,
either all-digits or all-digits followed by an 'x').


By comparison, a simple loop-based approach:

def isanum3(str):
    for c in str:
        if not c in string.digits: return 0
    return 1

takes around 480 milliseconds under the same conditions.


A map-based approach:

def isanum4(str):
    return not -1 in map(string.digits.find,str)

takes 280 milliseconds.


A reduce-based approach:

def isanum5(str):
    return reduce(lambda x,y: x and y in string.digits, str, 1)

takes about 3600 milliseconds -- lambda may be a
cool idea, but, speed-wise, it's NOT that great...


Alex






More information about the Python-list mailing list