isnumeric (mhlib.py)

Greg Jorgensen gregj at pobox.com
Thu Jan 4 19:58:46 EST 2001


"Richard van de Stadt" <stadt at cs.utwente.nl> wrote in message
news:3A548B2A.B45DC580 at cs.utwente.nl...
> Hi,
>
> I needed a function to check if a string is a number....

My stab at the Pythonic way:

# isnumeric - return 1 if argument is a valid number (integer or floating
point), 0 if not
def isnumeric(s):
    try:
        v = float(s)
        return 1
    except:
        return 0

>>> isnumeric('123')
1
>>> isnumeric(123)
1
>>> isnumeric('')
0
>>> isnumeric('greg')
0
>>> isnumeric('10E+6')
1

etc.

If you want to check for valid integers only change the float() to int().

--
Greg Jorgensen
PDXperts
Portland, Oregon, USA
gregj at pobox.com





More information about the Python-list mailing list