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 toisdigit()but includes Unicode numeric charactersisdecimal()– even stricter thanisdigit()
Interview Tip
Use isdigit() to filter numeric strings during input validation, form parsing, or data cleaning.
Summary
isdigit()returnsTrueif all characters are digits (0–9)- Returns
Falsefor 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.")
Comments
Loading comments...