Python string isdecimal() Method (original) (raw)
Last Updated : 30 Dec, 2024
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.
Python `
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
`
Table of Content
- Syntax of isdecimal()
- Example 1: Decimal Point Characters
- Example 2: Strings with Spaces or Symbols
- Example 3: Non-Decimal Numeric Characters
- Example 4: Negative Numbers or Symbols
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.
Python `
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
`
Example 2: Strings with Spaces or Symbols
The isdecimal() method does not consider spaces or symbols as decimal characters. Let’s see an example:
Python `
d = "12 34" print(d.isdecimal())
This will print False because there’s a space between the numbers
`
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.
Python `
c = "١٢٣٤٥" # Arabic-Indic numerals print(c.isdecimal()) # True, because these characters are considered decimal in their script
`
- However, if the characters belong to a different set, like Roman numerals or fractions, the method will return False. Python `
d = "Ⅻ" # Roman numeral for 12 print(d.isdecimal()) # False, Roman numerals are not decimal
`
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.
Python `
g = "-12345" print(g.isdecimal()) # False, because of the negative sign
h = "$12345" print(h.isdecimal()) # False, because of the '$' symbol
`