Python isdigit vs isnumeric vs isdecimal: Key Differences and Usage
isdigit() checks if all characters in a string are digits, including superscripts and subscripts. isnumeric() is broader and returns True for numeric characters like fractions and Roman numerals. isdecimal() is the strictest, only True for decimal digit characters (0-9).Quick Comparison
Here is a quick table comparing isdigit(), isnumeric(), and isdecimal() methods in Python based on key factors.
| Feature | isdigit() | isnumeric() | isdecimal() |
|---|---|---|---|
| Checks digits 0-9 | Yes | Yes | Yes |
| Includes superscripts/subscripts | Yes | Yes | No |
| Includes numeric characters like fractions, Roman numerals | No | Yes | No |
| Strict decimal digits only | No | No | Yes |
| Returns True for numeric strings only | No (some numeric chars excluded) | Yes | No (only decimals) |
| Use case | Basic digit check | Broad numeric check | Strict decimal digit check |
Key Differences
isdigit() returns True if all characters in the string are digits, including Unicode digits like superscripts and subscripts, but it excludes numeric characters like fractions or Roman numerals.
isnumeric() is more inclusive and returns True for all numeric characters, including digits, fractions, Roman numerals, and other numeric symbols defined in Unicode.
isdecimal() is the most strict and returns True only if all characters are decimal digits (0-9). It excludes superscripts, subscripts, and other numeric characters.
In summary, isdecimal() is for strict decimal digits, isdigit() includes more digit types, and isnumeric() covers all numeric characters.
Code Comparison
Example using isdigit() to check various strings:
samples = ['123', '²³', '½', 'IV', '10'] for s in samples: print(f"{s}: {s.isdigit()}")
isnumeric() Equivalent
Using isnumeric() on the same strings shows broader acceptance of numeric characters:
samples = ['123', '²³', '½', 'IV', '10'] for s in samples: print(f"{s}: {s.isnumeric()}")
When to Use Which
Choose isdecimal() when you need to ensure the string contains only decimal digits (0-9), such as validating simple numbers. Use isdigit() when you want to accept digits including superscripts or subscripts but not other numeric forms. Opt for isnumeric() when you want to accept any numeric character, including fractions and Roman numerals, for broader numeric validation.
Key Takeaways
isdecimal() is strictest, only decimal digits (0-9).isdigit() includes digits plus superscripts and subscripts.isnumeric() covers all numeric characters, including fractions and Roman numerals.isdecimal() for strict number validation, isnumeric() for broad numeric checks.