Difference between str.isdigit() and str.isdecimal() in Python 3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 16 20:15:26 EDT 2012


On Wed, 16 May 2012 17:48:19 +0200, Marco wrote:

> Hi all, because
> 
> "There should be one-- and preferably only one --obvious way to do it",
> 
> there should be a difference between the two methods in the subject, but
> I can't find it:

The Fine Manual has more detail, although I admit it isn't *entirely* 
clear what it is talking about if you're not a Unicode expert:


http://docs.python.org/py3k/library/stdtypes.html#str.isdecimal

str.isdecimal()
    Return true if all characters in the string are decimal characters 
and there is at least one character, false otherwise. Decimal characters 
are those from general category “Nd”. This category includes digit 
characters, and all characters that can be used to form decimal-radix 
numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.

str.isdigit()
    Return true if all characters in the string are digits and there is 
at least one character, false otherwise. Digits include decimal 
characters and digits that need special handling, such as the 
compatibility superscript digits. Formally, a digit is a character that 
has the property value Numeric_Type=Digit or Numeric_Type=Decimal.


And also:

str.isnumeric()
    Return true if all characters in the string are numeric characters, 
and there is at least one character, false otherwise. Numeric characters 
include digit characters, and all characters that have the Unicode 
numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, 
numeric characters are those with the property value Numeric_Type=Digit, 
Numeric_Type=Decimal or Numeric_Type=Numeric.


Examples:

py> c = '\u2155'
py> print(c)
⅕
py> c.isdecimal(), c.isdigit(), c.isnumeric()
(False, False, True)
py> import unicodedata
py> unicodedata.numeric(c)
0.2

py> c = '\u00B2'
py> print(c)
²
py> c.isdecimal(), c.isdigit(), c.isnumeric()
(False, True, True)
py> unicodedata.numeric(c)
2.0


-- 
Steven



More information about the Python-list mailing list