How to check if a string is a number in Python

Sometimes you want to validate user input to check if a string is a number. Using this simple function, you can check very easily!

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

print is_number("foo") # "False"
print is_number("baz") # "False"

print is_number("1") # "True"
print is_number(1.3) # "True"
print is_number(-1.37) # "True"

print is_number(1e3) # "True"

Tags: , , , ,

One Response to “How to check if a string is a number in Python”

  1. Ashwini Chaudhary March 31, 2012 at 4:45 pm #

    The isdigit() method is already available in python to check whether a String is a number or not.

    >>>str = "1234";

    >>>print str.isdigit()

    True

Leave a Reply