Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Remove All Occurrences of Substring

Remove all nonoverlapping substring matches with Python replace. Students preserve unmatched text and distinguish literal matching from regular expressions.

IntermediatePhase 5 - Category 4: String TransformationExample 9 of 10
remove-all-occurrences-of-substring.py
1# Take string input
2s = input("Enter a string: ")
3substring = input("Enter substring to remove: ")
4
5# Remove substring
6result = 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. 1

    Read s and substring.

  2. 2

    Call s.replace(substring, empty text).

  3. 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.