Remove All Occurrences of Substring
Remove all nonoverlapping substring matches with Python replace. Students preserve unmatched text and distinguish literal matching from regular expressions.
1# Take string input2s = input("Enter a string: ")3substring = input("Enter substring to remove: ")45# Remove substring6result = s.replace(substring, "")7print(f"After removal: {result}")
Output
Enter a string: Hello World Hello Enter substring to remove: Hello After removal: World
In this one
- Remove nonoverlapping matches
- Distinguish literals from patterns
- Keep unmatched text
How it works
- 1
Read s and substring.
- 2
Call s.replace(substring, empty text).
- 3
Print the returned removal result.
Edge cases
What if the substring is absent?
What if the substring is absent?
The content is unchanged.
What does removing aa from aaa leave?
What does removing aa from aaa leave?
One a, because matches do not overlap.
What's going on
s.replace(substring, "") matches literal text, not a regular expression. Each nonoverlapping match is replaced by nothing.
For banana and an, both matches are removed and ba remains. Matching is case-sensitive. Overlapping opportunities are not repeatedly reconsidered as separate original matches; this is a single replacement operation rather than an iterative cleanup until nothing else can form.
What if the substring is absent? The content is unchanged.
What does removing aa from aaa leave? One a, because matches do not overlap.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does replace interpret regex symbols?
Pick an answer to check it.
Question 2
What if the substring is absent?
Pick an answer to check it.
Questions people ask
What if the substring is absent?
The content is unchanged.
What does removing aa from aaa leave?
One a, because matches do not overlap.
Does replace interpret regex symbols?
No, it uses literal text.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum