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

Fredrik Lundh fredrik at effbot.org
Mon Nov 6 14:52:36 EST 2000


Alex Martelli wrote:
> 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'...):

SRE caches up to 100 patterns.

> 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

possible (minor) speedups: use default arguments to bind
the match method to a local variable slot, and use "is not"
instead of "!=".

def isanum1(str, match=all_digits.match):
    return match(str) is not None

:::

also note that a match object always evaluates to
true, so you can skip the None test; it only converts
one true value to another:

def isanum1(str, match=all_digits.match):
    return match(str)

this can be simplified:

isanum1 = all_digits.match

or, in other words:

isanum1 = re.compile(r'\d*$').match

all in all, this is about 10% faster than the original.

:::

> 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').

in theory, the match solution should be faster than search, but
it depends on the exact pattern, how your compiler expands in-
lined functions, what Python version you're using, and the phase
of the moon.

</F>





More information about the Python-list mailing list