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")
Code language: YAML (yaml)

should return false:

isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero")
Code language: Python (python)

Test cases

test.assert_equals(isDigit("s2324"), False) test.assert_equals(isDigit("-234.4"), True)
Code language: Python (python)

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
Code language: Python (python)

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))
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments