How to check if a String is a Number in Python

0 min read 119 words

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags