[Tutor] how to tell if strings have numbers in them

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 4 Jan 2001 19:15:00 +0100


On Thu, Jan 04, 2001 at 05:39:18PM -0000, alan.gauld@bt.com wrote:
> > a list of 0-9 and tried for z in x/if z in list, and that 
> > seems to work,  but its takes a lot of typing, is there 
> > an existing function 
> 
> import string
> if x in string.digits:
>    # do it here

Someone else already posted this, but not many people seem aware of it. (I
know I wasn't). In Python 2.0, strings have the useful isdigit() method,
that tests if all characters in the strings are digits:

>>> x="123"
>>> x.isdigit()
1
>>> x="123a"
>>> x.isdigit()
0

Nifty. There are several more methods as well, see dir(x) and their
docstrings.

-- 
Remco Gerlich