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
for text in ["12345", "123a5", "", " 42", "-7", "3.5"]: print(f"{text!r:9} {text.isdigit()}")
'12345' True '123a5' False '' False ' 42' False '-7' False '3.5' False
How it works
{text!r}prints the string with its quotes, so you can see the empty string and the space in' 42'.:9pads it to 9 characters, so the second column lines up.- An empty string gives
False, because it has no digits at all. - A space, a minus sign and a decimal point are not digits. So
isdigit()isFalsefor" 42","-7"and"3.5", even though people read them as numbers.
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:
print("²".isdigit()) print("²".isdecimal())
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:
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)}")
'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.