PythonMastery
Python programs · Strings · beginner

Check if a string contains only digits in Python

Test whether text is made only of digits with isdigit() and isdecimal(), what they say about spaces, minus signs and decimals, and a safer int() check.

isdigit() is True when a string has at least one character and every character is a digit. It is a quick way to check typed input before you turn it into a number.

The program

python
for text in ["12345", "123a5", "", " 42", "-7", "3.5"]:
    print(f"{text!r:9} {text.isdigit()}")
output
'12345'   True
'123a5'   False
''        False
' 42'     False
'-7'      False
'3.5'     False

How it works

isdigit() or isdecimal()?

isdigit() also accepts some special digit characters, such as the small raised ² in "x²". int() cannot convert those. isdecimal() accepts only the characters that int() can use:

python
print("²".isdigit())
print("²".isdecimal())
output
True
False

A safer check: try int()

To accept everything int() accepts (spaces around the number, a minus sign), try the conversion and catch the ValueError:

python
def is_whole_number(text):
    try:
        int(text)
        return True
    except ValueError:
        return False


for text in ["42", " 42 ", "-7", "3.5", "forty"]:
    print(f"{text!r:8} {is_whole_number(text)}")
output
'42'     True
' 42 '   True
'-7'     True
'3.5'    False
'forty'  False

int() ignores spaces at the start and the end, and accepts a sign. It still rejects "3.5": use float() in the same way if decimals are allowed.

Learn the idea: Working with Strings, Errors & Exceptions: When Things Go Wrong