The difference between Isnumeric vs isdigit vs isdecimal in Python is some may not work as you’d expect.
String Type | Example | Python .isdecimal() | Python .isdigit() | Python .isnumeric() |
---|---|---|---|---|
Base 10 Numbers | '0123' | True | True | True |
Fractions and Superscripts | '⅔', '2²' | False | True | True |
Roman Numerals | 'ↁ' | False | False | True |
isdigit
method returnsTrue
is all the characters in a string are digits, andFalse
if not.isnumeric
method has a number of key differences from the Python isdigit method. While theisidigit
method checks whether the string contains only digits, theisnumeric
method checks whether all the characters are numeric.isdecimal
method is a bit different, in that it evaluates whether a character is a decimal character, rather than a numeric character. Because of this, it will only returnTrue
if all the characters can evaluate to a base ten number, meaning that fractions and superscripts will returnFalse
.
s.isdigit()
s.isnumeric()
s.isdecimal()
By definition, isdecimal()
⊆ isdigit()
⊆ isnumeric()
. That is, if a string is decimal
, then it’ll also be digit
and numeric
.
Therefore, given a string s
and test it with those three methods, there’ll only be 4 types of results.
+-------------+-----------+-------------+----------------------------------+
| isdecimal() | isdigit() | isnumeric() | Example |
+-------------+-----------+-------------+----------------------------------+
| True | True | True | "038", "੦੩੮", "038" |
| False | True | True | "⁰³⁸", "🄀⒊⒏", "⓪③⑧" |
| False | False | True | "↉⅛⅘", "ⅠⅢⅧ", "⑩⑬㊿", "壹貳參" |
| False | False | False | "abc", "38.0", "-38" |
+-------------+-----------+-------------+----------------------------------+
Isnumeric vs isdigit vs isdecimal Python example
Simple example code difference between isdigit(), isnumeric(), and isdecimal().
def spam(s):
for attr in 'isnumeric', 'isdecimal', 'isdigit':
print(attr, getattr(s, attr)())
spam('½')
spam('³')
spam('Hello')
spam('123')
spam('1A')
Output:
Do comment if you have any doubts or suggestions on this Python methods comparison topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.