Python – Check if String Represents a Number (Float or Int)

castingfloating-pointpythontype-conversion

How do I check if a string represents a numeric value in Python?

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

The above works, but it seems clunky.


If what you are testing comes from user input, it is still a string even if it represents an int or a float. See How can I read inputs as numbers? for converting the input, and Asking the user for input until they give a valid response for ensuring that the input represents an int or float (or other requirements) before proceeding.

Best Answer

For non-negative (unsigned) integers only, use isdigit():

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

Documentation for isdigit(): Python2, Python3

For Python 2 Unicode strings: isnumeric().