Skip to content

Isnumeric vs isdigit Python

  • by

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:

  1. 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 return True for '123', but it will return False for '²³½'.
  2. 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 return True for '123', '²³½', and even '⅔' (Vulgar Fraction Two Thirds).

Here’s a tabular comparison between isnumeric() and isdigit() in Python:

MethodReturns True for Numeric CharactersRecognizes Other Numeric Characters (e.g., fractions)Returns True for Non-Numeric Characters
isdigit()Digits (0-9)NoNo
isnumeric()Digits (0-9) and Other NumericsYesNo

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 Stringisdigit()isnumeric()
'123'TrueTrue
'²³½'FalseTrue
'⅔'FalseTrue
'abc'FalseFalse

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:

Isnumeric vs isdigit Python

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.

Leave a Reply

Your email address will not be published. Required fields are marked *