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

Christian Tismer tismer at tismer.com
Mon Nov 6 08:24:19 EST 2000


Alex Martelli wrote:
> 
> "Gaute B Strokkenes" <gs234 at cam.ac.uk> wrote in message
> news:4a8zqyqxqv.fsf at kern.srcf.societies.cam.ac.uk...
>     [snip]
> > def isanum(str):
> >     # FIXME: Surely there must be a sane way of doing this.
> >     from string import find, digits
> >     for i in range(len(str)):
> >         if find(digits, str[i]) == -1:
> >             return 0
> >     return 1
> 
> There are many ways to check if all characters in the
> string are digits -- which is NOT necessarily the same
> as checking whether the string represents a valid
> "number", depending on what exactly one means --

<many nice variations snipped>

> Are these 'sane'...?  Nah.  re.match is really the
> only one worth thinking of for this specific case!
> 
> But it's fun to think of alternatives, and they're
> worth keeping in mind for other, similar tasks in
> which re would become bothersome... (plus, one
> can show off, "look, ma, no re!":-).

Well, so let me add one more, surely insane, but most
probably (without measuring) belonging to the fastest
possible variations...

The idea:
Instead of testing each character whether it belongs to the
set of digits, we use a cheap string mapping function
and categorize all characters.

Version 1:
We map all numeric characters to " " and all others to "n".
Doing a string.split() and counting the list length
tells us whether we have all numeric characters.

-----------------------------------------------------
import string

tlator = ["n"]*256
tlator[ord("0"):ord("9")+1] = [" "]*10
tlator = string.join(tlator, "")

def isanum(s):
    return len(string.split(string.translate(s, tlator))) == 0

Version 2:
We map all numeric characters to the empty string and leave
everything else. The resulting string must be empty.

-----------------------------------------------------

import string

tlator2=string.maketrans("","") # identity mapping

def isanum2(s):
    return len(string.translate(s, tlator2, "0123456789")) == 0

-----------------------------------------------------

I'd like to know what is faster: One of these string.translate
variations, or the new SRE engine?

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list