Using the isdigit() Method in Python

What is Python isdigit() Method and How to Use it?

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.

There are a few related concepts that can help you understand the isdigit() method better. These are:

  1. isnumeric() Method The isnumeric() method is similar to the isdigit() method. The difference is that isnumeric() returns True for all numeric characters, including digits, fractions, subscripts, superscripts, Roman numerals, currency numerators, and so on. string.isnumeric()
  2. isdecimal() Method The isdecimal() method is also similar to the isdigit() method. The difference is that isdecimal() returns True 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.