Python Reference · String Methods
Python str.isdigit() method
Reference for Python str.isdigit(): check that a string contains only digit characters, why superscripts pass, and why it is not a reliable int() test.
The isdigit() method returns True if the string is not empty and every character is a digit. Digits include the decimal digits (0 to 9 and their counterparts in other scripts) and also characters that are digits by Unicode's definition but cannot form ordinary numbers, such as superscripts (²) and circled digits (①).
For plain input checks like "is this a number made of 0-9?", isdigit() works on ASCII text, but isdecimal() is the more precise choice.
print("007".isdigit()) # True print("-7".isdigit()) # False
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.isdigit()
This method takes no parameters.
Return value: True if the string has at least one character and every character is a digit (Unicode numeric type "Digit" or "Decimal"); otherwise False.
Raises: nothing.
Usage notes
- Empty means
False."".isdigit()isFalse. - Only digit characters. A sign, decimal point, comma, space or exponent makes the result
False."-5"and"3.14"are not digit strings. - Superscripts and circled digits pass.
"²".isdigit()and"①".isdigit()areTrue, butint("²")andint("①")raiseValueError. Do not useisdigit()alone to decide whetherint()is safe; useisdecimal()or catch the exception. - Fractions and Roman numerals fail.
"½"and"Ⅳ"are numeric characters but not digits; seeisnumeric()for those. - Other scripts count. Arabic-Indic digits like
"٣"returnTrue. If you must accept only0-9, combine withisascii(). - Hierarchy. Every decimal character is a digit and every digit is numeric, so
isdecimal()is the narrowest test andisnumeric()the widest. - Bytes version.
bytes.isdigit()andbytearray.isdigit()exist and only accept ASCII0to9.