This guide explains Find a Substring Before Replacing It through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A text replacement should often check for the target first. .find() returns -1 for a missing substring, and .replace() returns a new string even when nothing matches.
When You Would Use This
Update a draft notice only if it contains the old product code.
Step-by-Step Example
notice = "Delivery for item-A is scheduled"
old_code = "item-A"
if old_code in notice:
updated_notice = notice.replace(old_code, "item-B")
print(updated_notice)
else:
print("Code not found")
How the Example Works
Membership checks the substring, then replacement creates a new string with the updated code. The original notice is unchanged.
Example Output
Delivery for item-B is scheduled
Try It Yourself
Replace just the first occurrence of "draft" in a longer message using the count argument.
Common Beginner Mistakes
- Assuming
.replace()mutates the original string. - Replacing short substrings that also occur inside unrelated words.
- Confusing a missing
.find()result of -1 with a valid location.
Key Takeaways
- A text replacement should often check for the target first.
- Membership checks the substring, then replacement creates a new string with the updated code.
- Avoid this mistake: Assuming
.replace()mutates the original string.