🔍 Checking String Content
Python provides several methods to check and validate the content of strings. These methods are essential for data validation, input processing, and text analysis.
# Basic string content checking
text = "Python123"
print(f"Is alphanumeric: {text.isalnum()}")
print(f"Is alphabetic: {text.isalpha()}")
print(f"Is numeric: {text.isdigit()}")
🎯 String Validation Methods
Python offers a variety of methods to check string content and characteristics.
Basic Examples
# Different ways to check string content
texts = ["Python", "123", "Python123", " ", "Hello World"]
for text in texts:
print(f"\nChecking '{text}':")
print(f"isalpha(): {text.isalpha()}")
print(f"isdigit(): {text.isdigit()}")
print(f"isalnum(): {text.isalnum()}")
print(f"isspace(): {text.isspace()}")
🔍 Pattern Matching
You can check if strings match specific patterns or contain certain content.
# Pattern matching examples
email = "user@example.com"
filename = "document.pdf"
text = "Hello World"
# Check if contains specific text
print(f"Contains 'World': {'World' in text}")
print(f"Contains '@': {'@' in email}")
# Check start and end
print(f"Starts with 'user': {email.startswith('user')}")
print(f"Ends with '.pdf': {filename.endswith('.pdf')}")
# Check case
print(f"Is lowercase: {text.islower()}")
print(f"Is uppercase: {text.isupper()}")
🎨 Common Use Cases
Here are some practical examples of string content checking.
# 1. Validating user input
def validate_username(username):
if not username.isalnum():
return "Username must contain only letters and numbers"
if not username[0].isalpha():
return "Username must start with a letter"
return "Valid username"
# 2. Checking file types
def is_valid_image(filename):
return filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))
# 3. Validating email format
def is_valid_email(email):
return '@' in email and '.' in email.split('@')[1]
# Test the functions
print(validate_username("user123"))
print(is_valid_image("photo.jpg"))
print(is_valid_email("user@example.com"))
📝 Quick Practice
Let's practice checking string content with a real-world scenario!
Hands-on Exercise
Create a function to validate a password.
python
# Password Validation Practice
def validate_password(password):
# TODO: Implement password validation
# 1. Check if password is at least 8 characters
# 2. Check if it contains at least one uppercase letter
# 3. Check if it contains at least one digit
# 4. Check if it contains at least one special character
# Return True if valid, False if invalid
return False
# Test the function
test_passwords = ["abc123", "Password123", "Pass123!", "P@ssw0rd"]
for pwd in test_passwords:
print(f"Password '{pwd}': {validate_password(pwd)}")Solution and Explanation 💡
Click to see the solution
# Password Validation Solution
def validate_password(password):
# Check length
if len(password) < 8:
return False
# Check for uppercase
if not any(c.isupper() for c in password):
return False
# Check for digit
if not any(c.isdigit() for c in password):
return False
# Check for special character
if password.isalnum():
return False
return True
# Test the function
test_passwords = ["abc123", "Password123", "Pass123!", "P@ssw0rd"]
for pwd in test_passwords:
print(f"Password '{pwd}': {validate_password(pwd)}")
Key Learning Points:
- 📌 Used
len()to check length - 📌 Used
any()with generator expressions - 📌 Used
.isupper()and.isdigit()for character checks - 📌 Used
.isalnum()to check for special characters
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.