Python string isdecimal() Method
In Python, the isdecimal() method is a quick and easy way to check if a string contains only decimal digits. It works by returning True when the string consists of digits from 0 to 9 and False otherwise. This method is especially useful when we want to ensure that user inputs or string data are strictly numeric without any special characters or spaces.
a = "12345"
print(a.isdecimal()) # This will print True as all characters are digits
b = "12345a"
print(b.isdecimal()) # This will print False because 'a' is not a decimal character
Output
True False
Table of Content
Syntax of isdecimal()
string.isdecimal()
Parameters
- The isdecimal() method does not take any parameters. It is simply called on a string object.
Return Type
The method returns:
- True if all characters in the string are decimal characters (i.e., digits 0-9).
- False if any character is not a decimal character (including symbols, spaces, letters, etc.) or if the string is empty.
Example 1: Decimal Point Characters
A string that contains a decimal point or any other non-digit characters will return False. For example, strings like "123.45" or "100,000" will fail the check because the period (.) and the comma (,) are not considered decimal digits.
e = "123.45"
print(e.isdecimal()) # False, because '.' is not a decimal character
f = "100,000"
print(f.isdecimal()) # False, because ',' is not a decimal character
Output
False False
Example 2: Strings with Spaces or Symbols
The isdecimal() method does not consider spaces or symbols as decimal characters. Let’s see an example:
d = "12 34"
print(d.isdecimal())
# This will print False because there’s a space between the numbers
Output
False
Example 3: Non-Decimal Numeric Characters
There are certain numeric characters from other writing systems or formats that look like digits but are not considered decimal digits in Python. For example, the Arabic-Indic numerals or other scripts that represent numbers differently.
c = "١٢٣٤٥" # Arabic-Indic numerals
print(c.isdecimal()) # True, because these characters are considered decimal in their script
Output
True
- However, if the characters belong to a different set, like Roman numerals or fractions, the method will return False.
d = "Ⅻ" # Roman numeral for 12
print(d.isdecimal()) # False, Roman numerals are not decimal
Output
False
Example 4: Negative Numbers or Symbols
The isdecimal() method also returns False when the string contains negative signs (-) or other symbols like currency symbols ($, €, etc.). The presence of any non-decimal character will cause the method to return False.
g = "-12345"
print(g.isdecimal()) # False, because of the negative sign
h = "$12345"
print(h.isdecimal()) # False, because of the '$' symbol
Output
False False