The isdigit()
method is a built-in method in Python that checks whether a string contains only digits or not. A digit is a character in the range 0 through 9, or a character that is considered a digit in the Unicode character set.
Syntax
The syntax of the isdigit()
method is as follows:
string.isdigit()
Here, string
is the string that we want to check for digits.
Return Value
The isdigit()
method returns True
if all the characters in the string are digits, otherwise it returns False
.
Examples
Here are three different examples of how to use the isdigit()
method in Python:
Example 1: Checking if a String Contains Only Digits
The following example demonstrates how to use the isdigit()
method to check if a string contains only digits:
string = "1234" result = string.isdigit() print(result)
Output:
True
In this example, we define a string “1234” and use the isdigit()
method to check whether all the characters in the string are digits. Since all the characters in the string are digits, the method returns True
.
Example 2: Checking if a String Contains Non-Digit Characters
The following example demonstrates how to use the isdigit()
method to check if a string contains non-digit characters:
string = "1234abc" result = string.isdigit() print(result)
Output:
False
In this example, we define a string “1234abc” and use the isdigit()
method to check whether all the characters in the string are digits. Since the string contains non-digit characters, the method returns False
.
Example 3: Using the isdigit() Method in a Loop
The following example demonstrates how to use the isdigit()
method in a loop:
strings = ["1234", "abc123", "12.34"] for string in strings: result = string.isdigit() print(f"{string}: {result}")
Output:
1234: True abc123: False 12.34: False
In this example, we define a list of strings and use a loop to iterate over each string in the list. We use the isdigit()
method to check whether all the characters in each string are digits. The output shows the result of the method for each string in the list.
Example 4: Checking Digits in Unicode (Hindi)
The following example demonstrates how to use the isdigit()
method to check digits in Hindi:
string = "१२३४" result = string.isdigit() print(result)
Output:
True
In this example, we define a string “१२३४” in Hindi and use the isdigit()
method to check whether all the characters in the string are digits. Since all the characters in the string are digits in Hindi, the method returns True
.
Use Cases
The isdigit()
method can be useful in a variety of scenarios, such as:
- Validating user input to ensure that it only contains digits
- Checking if a string is a valid integer before converting it to an integer
- Validating input in a form to ensure that only digits are entered