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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

26 lines
Python 3.9+
def 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

stdout
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

  1. Use re.sub with the re.IGNORECASE flag for a more concise one-liner.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.