Python isdecimal() method


The Python isdecimal() method checks whether a string contains only decimal characters. This method exists only for unicode objects.

Note

Define a decimal string, just add the 'u' prefix to the string.

Related course: Complete Python Programming Course & Exercises

grammatical

isdecimal() method syntax.

str.isdecimal()

parameters

  • none

return value

Returns True if the string contains only decimal characters, and False if it does not.

example

The following example shows the use of the isdecimal() function.

str = u "this2009"
print (str.isdecimal())

str = u "23443434"
print (str.isdecimal())

The output of the above example is as follows.

False
True

isdecimal, isdigit, isnumeric

The three string methods, isdecimal, isdigit, and isnumeric, are all used to determine whether a string is a number, so why use three methods? What are their differences within?

  • isdecimal(): whether or not it is a decimal digit

  • isdigit(): whether or not it is a digital character

  • isnumeric(): whether all characters are numeric

We define a function to perform the verification.

def isnumber(s):
     print(s+' isdigit: ',s.isdigit())
     print(s+' isdecimal: ',s.isdecimal())
     print(s+' isnumeric: ',s.isnumeric())

Or in Python 3 f-string style:

def isnumber(s):
    print(f'{s} isnumeric {s.isnumeric()}')
    print(f'{s} isdecimal {s.isdecimal()}')
    print(f'{s} isdigit {s.isdigit()}')

So you can call:

>>> isnumber('123')
123 isnumeric True
123 isdecimal True
123 isdigit True
>>> 
>>> isnumber('123.0')
123.0 isnumeric False
123.0 isdecimal False
123.0 isdigit False
>>> 
>>> isnumber('II-III')
II-III isnumeric False
II-III isdecimal False
II-III isdigit False
>>>

For unicode values:

>>> isnumber("\u0030") # unicode for 0
0 isnumeric True
0 isdecimal True
0 isdigit True

>>> isnumber("\u00B2") # unicode fo ²
² isnumeric True
² isdecimal False
² isdigit True
>>>