🔍 Finding and Replacing Text
Python provides powerful methods to search for and replace text within strings. These operations are essential for text processing and data cleaning.
# Basic find and replace
text = "Hello World"
new_text = text.replace("World", "Python")
print(f"Original: {text}")
print(f"Replaced: {new_text}")
🎯 Finding Text
Python offers several methods to locate text within strings.
Basic Examples
# Different ways to find text
text = "Python is fun, Python is great"
# Find first occurrence
first_pos = text.find("Python")
print(f"First 'Python' at: {first_pos}")
# Find last occurrence
last_pos = text.rfind("Python")
print(f"Last 'Python' at: {last_pos}")
# Count occurrences
count = text.count("Python")
print(f"'Python' appears {count} times")
# Using index (raises error if not found)
try:
pos = text.index("Java")
except ValueError:
print("'Java' not found!")
🔄 Replacing Text
The .replace()
method is the primary tool for text replacement.
# Basic replacement
text = "Hello World"
new_text = text.replace("World", "Python")
print(f"Replaced: {new_text}")
# Multiple replacements
text = "cat, dog, cat, bird"
new_text = text.replace("cat", "mouse")
print(f"Replaced: {new_text}")
# Limiting replacements
text = "cat, dog, cat, bird"
new_text = text.replace("cat", "mouse", 1) # Replace only first occurrence
print(f"Limited replacement: {new_text}")
🎨 Common Use Cases
Here are some practical examples of finding and replacing text.
# 1. Cleaning data
text = "User123@email.com"
cleaned = text.replace("@", " [at] ")
print(f"Cleaned email: {cleaned}")
# 2. Formatting text
text = "hello world"
formatted = text.replace("h", "H").replace("w", "W")
print(f"Formatted: {formatted}")
# 3. Multiple replacements
text = "The price is $100.00"
cleaned = text.replace("$", "").replace(".00", "")
print(f"Cleaned price: {cleaned}")
📝 Quick Practice
Let's practice finding and replacing text in a real-world scenario!
Hands-on Exercise
Clean up a text containing sensitive information.
python
# Text Cleaning Practice
sensitive_text = """
User: john.doe@company.com
Phone: 555-123-4567
ID: 123-45-6789
"""
# TODO: Clean up the sensitive information
# 1. Mask email addresses
# 2. Mask phone numbers
# 3. Mask social security numbers
# Print the result
print("Cleaned text:")
print(cleaned_text)
Solution and Explanation 💡
Click to see the solution
# Text Cleaning Practice Solution
sensitive_text = """
User: john.doe@company.com
Phone: 555-123-4567
ID: 123-45-6789
"""
# Clean up the sensitive information
cleaned_text = sensitive_text
# Mask email
email_pos = cleaned_text.find("@")
if email_pos != -1:
username = cleaned_text[:email_pos].split(": ")[1]
domain = cleaned_text[email_pos:].split("\n")[0]
masked_email = f"User: {username[0]}***@{domain}"
cleaned_text = cleaned_text.replace(cleaned_text.split("\n")[1], masked_email)
# Mask phone
phone_pos = cleaned_text.find("555-")
if phone_pos != -1:
phone = cleaned_text[phone_pos:].split("\n")[0]
masked_phone = f"Phone: ***-***-{phone[-4:]}"
cleaned_text = cleaned_text.replace(cleaned_text.split("\n")[2], masked_phone)
# Mask SSN
ssn_pos = cleaned_text.find("123-45-")
if ssn_pos != -1:
ssn = cleaned_text[ssn_pos:].split("\n")[0]
masked_ssn = f"ID: ***-**-{ssn[-4:]}"
cleaned_text = cleaned_text.replace(cleaned_text.split("\n")[3], masked_ssn)
print("Cleaned text:")
print(cleaned_text)
Key Learning Points:
- 📌 Used
.find()
to locate sensitive information - 📌 Used string slicing to preserve parts of the data
- 📌 Used
.replace()
to update the text - 📌 Handled multiple types of sensitive data
🎯 Key Takeaways
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.