The isdigit()
method is a built-in method in Python that returns True
if all the characters in a given string are digits. Otherwise, it returns False
. This method is useful when you want to check if a string contains only digits or not.
Syntax
The syntax of the isdigit()
method is as follows:
string.isdigit()
Here, string
is the string that you want to check.
Parameters
The isdigit()
method doesn’t take any parameters.
Return Value
The isdigit()
method returns True
if all the characters in the string are digits. Otherwise, it returns False
.
Examples
Here are some examples that illustrate the usage of the isdigit()
method:
Example 1: Using isdigit()
Method
string = "1234"
print(string.isdigit()) # True
In this example, we have a string string
that contains only digits. The isdigit()
method returns True
because all the characters in the string are digits.
Example 2: Using isdigit()
Method
string = "1234abc"
print(string.isdigit()) # False
In this example, we have a string string
that contains both digits and non-digits. The isdigit()
method returns False
because not all the characters in the string are digits.
Example 3: Using isdigit()
Method
string = "abcd"
print(string.isdigit()) # False
In this example, we have a string string
that contains only non-digits. The isdigit()
method returns False
.
Example 4: Using isdigit()
Method
string = ""
print(string.isdigit()) # False
In this example, we have an empty string. The isdigit()
method returns False
.
Example 5: Using isdigit()
Method
string = "१२३४"
print(string.isdigit()) # True
In this example, we have a string string
that contains digits in a non-English language (Hindi). The isdigit()
method returns True
because all the characters in the string are digits.
Related Concepts
There are a few related concepts that can help you understand the isdigit()
method better. These are:
isnumeric()
Method Theisnumeric()
method is similar to theisdigit()
method. The difference is thatisnumeric()
returnsTrue
for all numeric characters, including digits, fractions, subscripts, superscripts, Roman numerals, currency numerators, and so on.string.isnumeric()
isdecimal()
Method Theisdecimal()
method is also similar to theisdigit()
method. The difference is thatisdecimal()
returnsTrue
only for decimal characters (0-9).string.isdecimal()
Conclusion
In conclusion, the isdigit()
method is a built-in method in Python that returns True
if all the characters in a given string are digits. It’s a useful method when you want to check if a string contains only digits or not. The isnumeric()
and isdecimal()
methods are related concepts that can help you understand the isdigit()
method better.