Contents
Python String isdecimal() method
Python String isdecimal() method is used to check if all characters in the string are decimal characters and there is at least one character in the string.
Consider that given string is in x.
x = "12345"
Then the return value of x.isdecimal() is
True
In this tutorial, you will learn the syntax and usage of String isdecimal() method in Python language.
Syntax of isdecimal() method
The syntax of String isdecimal() method in Python is given below.
str.isdecimal()
Parameters
The string isdecimal() method takes no parameters.
Return value
The string isdecimal() method returns a boolean value of True if all characters in the string are decimal characters and there is at least one character in the string, otherwise False.
Examples
1. Checking if given string has only decimal characters in Python
In this example, we take a string value in variable x. We have to check if all characters in the string are decimal.
Call isdecimal() method on the string object x and use the returned value as a condition in Python if else statement as shown in the following program.
Python Program
x = "12345"
if x.isdecimal():
print('Given string is DECIMAL.')
else:
print('Given string is NOT DECIMAL.')
Run Code CopySince all characters in the given string x are decimal, isdecimal() method returns True, and the if-block executes.
Output
Given string is DECIMAL.
2. isdecimal() with string containing special symbols in Python
In the following program, we take a string value in variable x such that some of the characters in the string are not decimal characters, like +, $, etc.
Since, not all characters in the string are decimal, isdecimal() method returns False, and the else-block executes.
Python Program
x = "$12345"
if x.isdecimal():
print('Given string is DECIMAL.')
else:
print('Given string is NOT DECIMAL.')
Run Code CopyOutput
Given string is NOT DECIMAL.
3. isdecimal() with an empty string
In the following program, we take an empty string value in variable x, and check the return value of isdecimal() for this empty string.
From the definition of isdecimal(), we know that the method returns False if the string is empty.
Python Program
x = ""
if x.isdecimal():
print('Given string is DECIMAL.')
else:
print('Given string is NOT DECIMAL.')
Run Code CopyOutput
Given string is NOT DECIMAL.
Summary
In this tutorial of Python String Methods, we learned about String isdecimal() method, its syntax, and examples.