How to check if a String is a Number in Python

The challenge

Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.

Valid examples, should return true:

isDigit("3")
isDigit("  3  ")
isDigit("-3.23")

should return false:

isDigit("3-4")
isDigit("  3   5")
isDigit("3 5")
isDigit("zero")

Test cases

test.assert_equals(isDigit("s2324"), False)
test.assert_equals(isDigit("-234.4"), True)

The solution in Python

Option 1(with try/except):

# create a function
def isDigit(string):
    # use a `try/except` block
    try:
        # True if can convert to a float
        float(string)
        return True
    except:
        # otherwise return False
        return False

Option 2(with regex/Regular expression):

# import the regex match module
from re import match

def isDigit(string):
    # return a Boolean if the match was met
    return bool(match(r"^[-+]?\d+\.?\d*?$", string))
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments