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:

1
2
3
isDigit("3")
isDigit("  3  ")
isDigit("-3.23")

should return false:

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

Test cases

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

The solution in Python

Option 1(with try/except):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 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):

1
2
3
4
5
6
# 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))