Python - How to check if a string is a number

By xngo on June 7, 2019

#!/usr/bin/python3
# Description: How to check if a string is a number.
 
def isNumber(str):
    try:
        float(str)
        return True
    except ValueError:
        return False
 
s = "1234"
print("is {} a number = {}".format(s, isNumber(s)))
 
s = "100.99"
print("is {} a number = {}".format(s, isNumber(s)))
 
s = "-5.66"
print("is {} a number = {}".format(s, isNumber(s)))
 
s = "01234"
print("is {} a number = {}".format(s, isNumber(s)))
 
s = "y1234"
print("is {} a number = {}".format(s, isNumber(s)))

Output

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.