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):
    try:
        float(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'.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →