isNumber? check

Tony Meyer ta-meyer at ihug.co.nz
Mon Sep 29 20:13:57 EDT 2003


Rob> I don't like that solution for this particular project because, as
Rob> you say yourself, if it says yes to the second question, it only
Rob> *may* be a number.  I want to know for sure.

This also works, although it may not be best for your situation (only does
int and float for brevity):

"""
def isInt(s):
    try:
        i = int(s)
    except ValueError:
        i = None
    return i
def isFloat(s):
    try:
        i = float(s)
    except ValueError:
        i = None
    return i
def isNumber(s):
    return isInt(s) or isFloat(s)
"""

One advantage is that it returns the number (as an int (preferable) or
float) rather than just True/False (None is returned if it is not able to be
turned into a number).  You're probably going to want to turn it into a
number at some point anyway, right?, so why not do it in one step.

Note that "0" will come back as 0.0, though, because it evaluates as False.
It would be easy enough to special case that, if necessary.

=Tony Meyer






More information about the Python-list mailing list