[Tutor] how to tell if strings have numbers in them
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:
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:
except: return 0
and it seems to work pretty well:
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!