Python String isdigit() Method
The isdigit()
method checks if all characters in a string are digits.
Syntax
string.isdigit()
Parameters
No Parameters.
Return Value
Returns True
if all characters in a string are digits. Unicode digit characters such as superscripts and subscripts are also considered digits.
Retruns False
if any character in a string is not a digit, or if the string is empty.
What Counts as Digits?
The isdigit()
method considers the following as digits:
- Digits (0-9)
- Superscripts and subscripts (¹, ₂)
- Digits from other scripts (Arabic: ٢, Devanagari: २)
The isdigit()
method does not recognize the following characters as digits:
- Fractions (e.g., ½, ¾)
- Roman numerals (e.g., Ⅻ)
- Most numeric symbols that aren’t classified as “digit” characters in Unicode.
Example
Check if a String is a Digit
print("123".isdigit()) # True
print("\u0035".isdigit()) # True (Unicode for 5)
print("²".isdigit()) # True (Superscript digit)
print("₃".isdigit()) # True (Subscript digit)
print('٢'.isdigit()) # True (2 in Arabic)
print("123.4".isdigit()) # False (contains decimal point)
print("123abc".isdigit()) # False (contains letters)
print("-123".isdigit()) # False (contains negative sign)
print("½".isdigit()) # False (Fractions)
isdigit()
vs isnumeric()
Both isdigit()
and isnumeric()
are used to check if characters in a string are numeric, but they have important differences in what they consider “numeric”.
Character Type | isdigit() | isnumeric() |
Basic Digits (0-9) | True | True |
Arabic Digits E.g., ٢ (2 in Arabic) | True | True |
Devnagari Digits e.g. १२ (12 in Devnagari) | True | True |
Superscripts (², ³) | True | True |
Subscripts (₁, ₂) | True | True |
Fractions (½, ¾) | False | True |
Roman Numerals (Ⅷ, Ⅻ) | False | True |
Floating Point Numbers (1.5) | False | False |
Negative Numbers (-5) | False | False |
Empty String ("" ) | False | False |