Python string isdigit() method with example

The isdigit() method in Python is a built-in method used for string handling. This method returns True if all the characters in the string are digits, otherwise it returns False.

Syntax:

str.isdigit()

How to use the isdigit() method:

str = "12345"
print(str.isdigit()) # Returns: True

str = "12345abc"
print(str.isdigit()) # Returns: False

Example 1

User Input Validation.

user_input = input("Please enter a number: ")
if user_input.isdigit():
  print("You entered number:", user_input)
else:
  print("Invalid input. Please enter a number.")

Example 2

Filtering a List.

list = ["123", "abc", "456", "789abc"]
numeric_list = [item for item in list if item.isdigit()]
print(numeric_list) # Returns: ['123', '456']

Leave a Reply

Your email address will not be published. Required fields are marked *