Both isnumeric()
and isdigit()
are methods in Python used to check whether a given string consists of numeric characters. However, there are some differences between the two methods:
isdigit()
:- This method returns
True
if all characters in the string are digits (0-9). - It does not recognize other numeric characters like superscripts, subscripts, or fractions.
- For example,
isdigit()
will returnTrue
for'123'
, but it will returnFalse
for'²³½'
.
- This method returns
isnumeric()
:- This method returns
True
if all characters in the string are numeric, including digits, superscripts, subscripts, fractions, and other numeric characters in different scripts. - It is more inclusive and recognizes a wider range of characters that represent numbers.
- For example,
isnumeric()
will returnTrue
for'123'
,'²³½'
, and even'⅔'
(Vulgar Fraction Two Thirds).
- This method returns
Here’s a tabular comparison between isnumeric()
and isdigit()
in Python:
Method | Returns True for Numeric Characters | Recognizes Other Numeric Characters (e.g., fractions) | Returns True for Non-Numeric Characters |
---|---|---|---|
isdigit() | Digits (0-9) | No | No |
isnumeric() | Digits (0-9) and Other Numerics | Yes | No |
In the table above, for the input string '123'
, both isdigit()
and isnumeric()
return True
because it consists only of digits.
For the input string ‘²³½’, isdigit() returns False as it contains non-digit characters, but isnumeric() returns True because it recognizes superscripts and fractions as numeric characters. For the input string 'abc'
, both methods return False
since it does not contain any numeric characters.
Example usage:
Input String | isdigit() | isnumeric() |
---|---|---|
'123' | True | True |
'²³½' | False | True |
'⅔' | False | True |
'abc' | False | False |
Isnumeric vs isdigit Python example
Here are some examples to illustrate the difference:
s1 = '123'
s2 = '²³½'
s3 = '⅔'
print(s1.isdigit())
print(s1.isnumeric())
print(s2.isdigit())
print(s2.isnumeric())
print(s3.isdigit())
print(s3.isnumeric()) # isnumeric() recognizes the vulgar fraction
Output:
In summary, if you want a more inclusive check for numeric characters, use isnumeric()
. If you only want to check if the string contains digits (0-9), use isdigit()
.
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.