How do I check if a string represents a number in Python?

Better Stack Team
Updated on February 3, 2023

To check if a string represents a number (float or int) in Python, you can try casting it to a float or int and check if the cast was successful. If the string can't be cast, then it is not a number.

Here is an example:

def is_number(s):
        return True
    except ValueError:
        return False

print(is_number('123'))  # True
print(is_number('123.456'))  # True
print(is_number('123a'))  # False
print(is_number('abc'))  # False

Alternatively, you can use the isdigit method of strings:

def is_number(s):
    return s.isdigit()

print(is_number('123'))  # True
print(is_number('123.456'))  # False
print(is_number('123a'))  # False
print(is_number('abc'))  # False

Note that the isdigit method will only return True for strings that consist only of digits and that do not have a decimal point. It will return False for strings like '123.456' or '123a'.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github