Python String isdigit() Method – Check If a String Has Only Digits

Python String isdigit() Method

The isdigit() method in Python checks whether all characters in a string are digits (0–9). It's a handy way to verify if a string represents a number.

Syntax

string.isdigit()

Parameters:

  • This method does not take any parameters.

Returns:

  • True – if all characters in the string are digits.
  • False – if the string has one or more non-digit characters.

Example 1: Basic Usage

text = "12345"
print(text.isdigit())
True

Example 2: Contains Letters

text = "123abc"
print(text.isdigit())
False

Example 3: Empty String

text = ""
print(text.isdigit())
False

Use Case: Validating User Input

The isdigit() method is commonly used to validate input from users. For example, when asking for age or mobile number:

age = input("Enter your age: ")
if age.isdigit():
    print("Valid age!")
else:
    print("Please enter digits only.")

Output Example:

Enter your age: 25
Valid age!

Common Mistakes

  • Does not allow negative numbers (e.g., "-123" → False)
  • Decimal numbers (e.g., "3.14") also return False

Related Methods

  • isnumeric() – similar to isdigit() but includes Unicode numeric characters
  • isdecimal() – even stricter than isdigit()

Interview Tip

Use isdigit() to filter numeric strings during input validation, form parsing, or data cleaning.

Summary

  • isdigit() returns True if all characters are digits (0–9)
  • Returns False for empty strings, decimals, or non-digit characters
  • Commonly used in input validation

Practice Problem

Write a program that asks for a PIN code and prints "Valid PIN" only if all characters are digits.

pin = input("Enter your 4-digit PIN: ")
if pin.isdigit() and len(pin) == 4:
    print("Valid PIN")
else:
    print("Invalid PIN. Please enter a 4-digit number.")
Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗