Remove All Occurrences of Substring

Remove all occurrences of a substring.

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 

What's going on

Use replace() to remove substring.

Key Concepts:

Replace substring with ""
All occurrences removed
Returns new string