Remove Substring Occurrences Case-Insensitively in Python
This code removes every case-insensitive occurrence of a given substring from a text string using a simple looping approach.
Python code
26 linesdef remove_occurrences_ci(text: str, substring: str) -> str:
"""Remove all case-insensitive occurrences of substring from text."""
if not substring:
return text
result = []
i = 0
lower_text = text.lower()
lower_sub = substring.lower()
sub_len = len(substring)
while i < len(text):
if lower_text[i:i+sub_len] == lower_sub:
i += sub_len
else:
result.append(text[i])
i += 1
return "".join(result)
if __name__ == "__main__":
sample_text = "The Quick Brown Fox jumps over the lazy dog. QUICK!"
print(remove_occurrences_ci(sample_text, "quick"))
print(remove_occurrences_ci("Hello World, hello again", "HELLO"))
print(remove_occurrences_ci("No matches here", "xyz"))
Output
The Brown Fox jumps over the lazy dog. !
World, again
No matches here
How it works
The function converts both the text and the substring to lowercase for case-insensitive comparison, then scans through the original text. When a match is found at the current position, it skips ahead by the length of the substring; otherwise, it appends the original character to the result. This preserves the original casing of non-matched characters while removing all occurrences regardless of case. The loop ensures overlapping matches are handled correctly by restarting the comparison after each removal.
Common mistakes
- Using str.replace() which is case-sensitive by default and does not handle case-insensitivity.
- Forgetting to handle the empty substring case, which can cause an infinite loop.
- Assuming that lowercasing the entire text changes the original case, but you must build the result from the original text.
Variations
- Use re.sub with the re.IGNORECASE flag for a more concise one-liner.
- Use a while loop with str.find() to locate and slice out occurrences.
Real-world use cases
- Cleaning user input by stripping out banned words regardless of capitalization in chat moderation.
- Removing duplicate tags from a search query string where case differences should be ignored.
- Sanitizing log messages to remove sensitive tokens that may appear in mixed case.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.