How to Use the Python String isdigit() Method

09/13/2021

Contents

In this article, you will learn how to use the Python string isdigit() method.

Python String isdigit() Method

The isdigit() method is a built-in string method in Python that returns True if all characters in the string are digits and False otherwise. Here’s how you can use the isdigit() method in Python:

# Example string
string = "12345"

# Check if all characters are digits
if string.isdigit():
    print("All characters are digits")
else:
    print("Not all characters are digits")

In the example above, the isdigit() method is called on the string variable string. Since all characters in the string are digits, the isdigit() method returns True, and the program prints the message “All characters are digits”.

Here’s another example that demonstrates how to use the isdigit() method to validate user input:

# Ask the user for input
user_input = input("Enter a number: ")

# Check if the input is a number
if user_input.isdigit():
    number = int(user_input)
    print(f"The number is {number}")
else:
    print("Invalid input. Please enter a number.")

In this example, the isdigit() method is used to check if the user input is a number. If the input is a number, the program converts it to an integer and prints the message “The number is [number]”. If the input is not a number, the program prints the message “Invalid input. Please enter a number.”