check on numerical value?

Jeff Epler jepler at unpythonic.net
Thu Jun 6 08:59:03 EDT 2002


You could see if eg float() will handle it:
    def isfloat(s):
        try:
            float(s)
        except ValueError:
            return False
        else:
            return True
This method will work on any type that defines a __float__ method as
well (eg an instance of a rational number class)

Or you could check it against a regular expression (only good for
strings, obviously):
    import re, tokenize
    _isfloat_re = re.compile(tokenize.Number + "$")
    def isfloat(s):
        if _isfloat_re.match(s): return True
        else: return False

(tokenize.Number recognizes hex, octal, and decimal integer constants;
floating point constants with and without exponents; and imaginary
numbers with the "J" or "j" suffix.  You might prefer to use
    DecFloat = tokenize.group(tokenize.PointFloat, tokenize.ExpFloat,
                              tokenize.DecNumber)
    _isfloat_re = re.compile(DecFloat + "$")
)

(True and False may not appear in your version of Python.  Substitute 1
and 0 if they're not there)

Jeff





More information about the Python-list mailing list