
Python
Combine everything you've learned to build practical, real-world string applications.
Parse and format full names:
def parse_full_name(full_name):
"""Extract first, middle, and last names"""
parts = full_name.strip().split()
first = parts[0]
last = parts[-1]
middle = " ".join(parts[1:-1]) if len(parts) > 2 else ""
return {
"first": first,
"middle": middle,
"last": last,
"full": full_name
}
# Usage
name = "John Michael Smith"
parsed = parse_full_name(name)
print(f"{parsed['first']} {parsed['middle']} {parsed['last']}")
# John Michael SmithFind all email addresses in text:
import re
def extract_emails(text):
"""Find all email addresses"""
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
return re.findall(pattern, text)
# Usage
text = "Contact john@example.com or jane.smith@company.org for details."
emails = extract_emails(text)
print(emails) # ['john@example.com', 'jane.smith@company.org']Convert titles to URL-friendly slugs:
def generate_slug(title):
"""Convert title to URL slug"""
# Convert to lowercase
slug = title.lower()
# Replace spaces with hyphens
slug = slug.replace(" ", "-")
# Remove special characters
import re
slug = re.sub(r"[^a-z0-9-]", "", slug)
# Remove multiple hyphens
slug = re.sub(r"-+", "-", slug)
# Remove leading/trailing hyphens
slug = slug.strip("-")
return slug
# Usage
title = "How to Learn Python Programming!!"
slug = generate_slug(title)
print(slug) # how-to-learn-python-programmingProcess CSV data safely:
def parse_csv_line(line):
"""Parse CSV line (simple version)"""
# Handle quoted fields with commas
fields = []
current = ""
in_quotes = False
for char in line:
if char == '"':
in_quotes = not in_quotes
elif char == "," and not in_quotes:
fields.append(current.strip())
current = ""
else:
current += char
fields.append(current.strip())
return fields
# Usage
csv_line = 'John,"123 Main St, Apt 4",NYC,30'
fields = parse_csv_line(csv_line)
print(fields) # ['John', '123 Main St, Apt 4', 'NYC', '30']Check password strength:
def check_password_strength(password):
"""Validate and score password"""
score = 0
feedback = []
# Length check
if len(password) >= 8:
score += 1
else:
feedback.append("At least 8 characters")
# Uppercase check
if any(c.isupper() for c in password):
score += 1
else:
feedback.append("Include uppercase letters")
# Lowercase check
if any(c.islower() for c in password):
score += 1
else:
feedback.append("Include lowercase letters")
# Digit check
if any(c.isdigit() for c in password):
score += 1
else:
feedback.append("Include numbers")
# Special character check
import re
if re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
score += 1
else:
feedback.append("Include special characters")
strength = ["Very Weak", "Weak", "Fair", "Good", "Strong", "Very Strong"]
return {
"score": score,
"strength": strength[score],
"suggestions": feedback
}
# Usage
result = check_password_strength("MyPass123!")
print(f"Strength: {result['strength']}")
print(f"Score: {result['score']}/5")Analyze text content:
def analyze_text(text):
"""Calculate text statistics"""
# Remove extra whitespace
clean_text = " ".join(text.split())
# Character count
char_count = len(clean_text)
# Word count
words = clean_text.split()
word_count = len(words)
# Sentence count
import re
sentences = re.split(r"[.!?]+", clean_text)
sentence_count = len([s for s in sentences if s.strip()])
# Average metrics
avg_word_length = char_count / word_count if word_count > 0 else 0
avg_sentence_length = word_count / sentence_count if sentence_count > 0 else 0
return {
"characters": char_count,
"words": word_count,
"sentences": sentence_count,
"avg_word_length": round(avg_word_length, 2),
"avg_sentence_length": round(avg_sentence_length, 2)
}
# Usage
text = "Python is amazing. It's easy to learn and powerful. Many developers love it!"
stats = analyze_text(text)
print(f"Words: {stats['words']}, Sentences: {stats['sentences']}")| Task | Pattern | Example |
|---|---|---|
| Extract email | `\w+@\w+\.\w+` | Find email addresses |
| Extract phone | `\d{3}-\d{3}-\d{4}` | Find phone numbers |
| Extract URL | `https?://[^\s]+` | Find web addresses |
| Extract hashtag | `#\w+` | Find social media tags |
| Format phone | Split and rejoin | `1234567890` → `123-456-7890` |
| Concept | Remember |
|---|---|
| Combine methods | Use split(), join(), replace() together |
| Validate input | Always check string properties before processing |
| Use regex for patterns | Complex matching needs regex |
| Handle edge cases | Empty strings, special characters, encoding |
| Test your code | Run with various inputs and edge cases |
You've completed String Manipulation! Ready for the next Python topic?
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward