This is a tutorial of the Python String isdigit() method. Learn to check if a given string only contains digit characters or not with examples.
str.isdigit() method returns True if the given string contains only digit characters (0-9, even in subscripts or superscripts) and if not it returns False.
Given below is the syntax of the
ifdigits = givenString.isdigit()
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.
isdigit() Return Value
It returns the boolean value
False according to the following logic.
Trueif all of the characters in the given string are only digits.
Falseif not all the characters in the given string are digits.
Given below are the two examples demonstrating the usage of the Python String
Example 1. Checking a given String contains all the digits or not using
In this example, we’re applying the method
isdigit() on several different strings to check the result, for what strings it returns
True and for what it returns
#String with only digits line = "1234567890" print(line.isdigit()) #String with digits and a whitespace line = "12345 67890" print(line.isdigit()) #String with digits and special symbols line = "12345?" print(line.isdigit()) #String with Alphanumeric Characters line = "Hello12345" print(line.isdigit()) #String with only Alphabets line = "Abcd" print(line.isdigit()) #String with Powers line = '12\u00B2' #represents '12^2' print(line.isdigit()) #String with Special Fractions line = "½" #Fractions are not accounted as digits print(line.isdigit()) #Floating Point Numbers #Not accounted as digits line = "5.7" print(line.isdigit())
True False False False False True False False
Example 2. Using the Python String
isdigit() method with if-else statement
In the following example, we’ve directly used the
str.isdigit() method as the condition for the if-else statement to print a string accordingly after checking if the given string only contains digits or not.
#Using str.isdigit() with if-else statement #Given String name = "HelloWorld12345" if name.isdigit(): print("name only contains digits.") else: print("name also contains characters other than digits.")
name also contains characters other than digits.
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!