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

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 3 Jan 2001 20:44:33 -0800 (PST)

On Wed, 3 Jan 2001, Brett wrote:

> I'm trying to get input and checking to see if it's a number.  x==int(x) 
> works if it is a number, but causes an error if you input a string.  I made 
> 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 that can check 
> to see if a variable is a number?

Hmmm... let's take a look:

>>> int("42")      
>>> int("forty-two")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): forty-two

I see, so it throws a ValueError if something goes wrong in the
conversion.  I can't think of a built-in isNumber() function that checks
if something is a number.  However, there are several nice ways of writing
one.  Here's one:

def isNumber(x):
    try: int(x)
    except: return 0
    return 1

and it seems to work pretty well:

>>> isNumber("forty-two")
>>> isNumber("42")
>>> isNumber(42)

This version of isNumber() depends on the fact that bad things will cause
exceptions: that's where isNumber() returns zero.  Otherwise, isNumber()
will be happy and return one.

You might not be familiar with try/except.  It's mentioned a little bit in
the official tutorial here:


Hope this helps!