This is a tutorial of the Python String isdecimal() method. Learn to check if a given string only contains decimal characters or not with examples.
Table of Contents
Python String isdecimal()
The str.isdecimal()
method returns True if the given string contains only decimal characters (0-9) and if not it returns False.
Syntax
Given below is the syntax of the str.isdecimal()
method.
1 |
ifDecimals = givenString.isdecimal() |
isdecimal()
Parameters
This method does not take any arguments as it only checks the characters in the string on which it is applied, so no additional data is required in the form of arguments.
isdecimal()
Return Value
It returns the boolean value True
or False
according to the following logic.
- Returns
True
if all of the characters in the given string are only decimals. - Returns
False
if not all the characters in the given string are decimals.
Examples
Given below are the two examples demonstrating the usage of the Python String isdecimal()
method.
Example 1. Checking a given String contains all the decimals or not using str.isdecimal()
method
In this example, we’re applying the method isdecimal()
on several different strings to check the result, for what strings it returns True
and for what it returns False
.
#String with only decimals line = "1234567890" print(line.isdecimal()) #String with decimals and a whitespace line = "12345 67890" print(line.isdecimal()) #String with decimals and special symbols line = "12345?" print(line.isdecimal()) #String with Alphanumeric Characters line = "Hello12345" print(line.isdecimal()) #String with only Alphabets line = "Abcd" print(line.isdecimal()) #String with Powers line = '12\u00B2' #represents '12^2' print(line.isdecimal()) #String with Special Fractions line = "½" print(line.isdecimal())
Output.
True False False False False False False
Example 2. Using the Python String isdecimal()
method with if-else statement
In the following example, we’ve directly used the str.isdecimal()
method as the condition for the if-else statement to print a string accordingly after checking if the given string only contains decimals or not.
#Using str.isdecimal() with if-else statement #Given String name = "HelloWorld12345" if name.isdecimal(): print("name only contains decimals.") else: print("name also contains characters other than decimals.")
Output.
name also contains characters other than decimals.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!