str.isdigit()
Returns True when a string is not empty and every character is a digit. Useful for checking input before int().
str.isdigit()isdigit() returns True when the string has at least one character and every character is a digit, such as "2026". An empty string, a space, a minus sign or a decimal point all make it False.
Its usual job is checking what a user typed before you convert it with int(), so the program does not crash on "abc".
Python has three similar checks, and they are not the same. isdecimal() accepts only the digits 0–9 (in any script). isdigit() also accepts digit-like signs such as the superscript "²". isnumeric() accepts even more, such as "½" and Roman numerals. Only isdecimal() guarantees that int() will work.
Return value
True or False.
Examples
1Simple checks
print("2026".isdigit())
print("12.5".isdigit())
print("-5".isdigit())
print("".isdigit())True False False False
A decimal point or minus sign is not a digit, so these need another check.
2Check input before converting
age = input("Age: ")
if age.isdigit():
print("Next year you will be", int(age) + 1)
else:
print("Please type a whole number")Age: Next year you will be 30
3isdecimal() vs isdigit() vs isnumeric()
samples = ["42", "²", "½", "٣", "Ⅻ"]
print("text decimal digit numeric")
for s in samples:
print(f"{s:<5} {s.isdecimal()!s:<7} {s.isdigit()!s:<5} {s.isnumeric()}")text decimal digit numeric 42 True True True ² False True True ½ False False True ٣ True True True Ⅻ False False True
"٣" is the Arabic-Indic digit three. "²" is a digit to isdigit() but not a decimal digit; "½" and "Ⅻ" are only numeric.
4Why isdigit() is not a guarantee for int()
text = "²"
print(text.isdigit())
try:
print(int(text))
except ValueError:
print("int() cannot read it")
print(text.isdecimal())True int() cannot read it False
5Keep only the digits of a phone number
phone = "+30 (210) 123-4567"
digits = "".join(c for c in phone if c.isdigit())
print(digits)302101234567
Common mistakes
Expecting isdigit() to accept negative or decimal numbers
"-3" and "2.5" contain characters that are not digits. To accept any number, try converting and catch the error.
for text in ["7", "-3", "2.5", "abc"]:
try:
value = float(text)
print(text, "is a number")
except ValueError:
print(text, "is not a number")7 is a number -3 is a number 2.5 is a number abc is not a number
Questions people ask
isdigit vs isnumeric vs isdecimal: which should I use?
To check text before int(), use isdecimal(): it accepts only real digits 0–9 (in any script). isdigit() also accepts superscripts like ², and isnumeric() also fractions like ½.
How do I check if a string is a float?
Use try: float(text) and catch ValueError. No string method understands "2.5" or "-3".
Why does " 42".isdigit() return False?
The space is not a digit. Clean the text with strip() first.
Does isdigit() work on an empty string?
It returns False, because there is no digit at all.