Python 3 – String isdigit() Method
The isdigit()
method is a built-in method in Python 3. It is used to check whether every character in a string is a digit or not. This method returns True if every character in a string is a digit, otherwise it returns False.
Syntax
The syntax for isdigit()
method is:
string.isdigit()
Example
To illustrate how the isdigit()
method works, let’s consider an example:
string1 = "1234"
string2 = "12a4"
print(string1.isdigit()) # Output: True
print(string2.isdigit()) # Output: False
In the example above, string1
only contains digits, therefore the isdigit()
method returns True. However, string2
contains the letter “a”, which is not a digit, and the isdigit()
method returns False.
Usage
The isdigit()
method can be used to verify if a string only contains digits. This is useful when dealing with user input forms, where the user may be required to enter a numeric value. You can use the isdigit()
method to ensure that the user inputs only digits.
Let’s see an example:
while True:
number = input("Enter a number: ")
if number.isdigit():
break
print("Invalid input. Please enter only digits.")
print("You entered:", number)
In the example above, the while
loop repeats until the user enters a valid input, which means only digits. If the user enters a non-digit value, the program prints an error message and repeats the loop until a valid input is received.
Conclusion
The isdigit()
method is an effective way to check whether a string contains only numeric characters or not. It is a useful method to include in your programming toolbox, especially when dealing with user input forms, which may require numeric values. By using the isdigit()
method, you can ensure that your program will only receive valid input from the user, and avoid potential errors caused by invalid input.