Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Replace a substring ignoring case

Replace all occurrences of a substring regardless of case, preserving non-matching text.

Python practice15 minString PatternsIntermediateLast updated March 18, 2026

Problem statement

Write a function replace_ignore_case(s, old, new) that returns a new string where every occurrence of old in s is replaced with new, ignoring case when matching old. Replacements should be non-overlapping (standard left-to-right behavior). If old is an empty string, return s unchanged. Use only the Python standard library. Examples: - replace_ignore_case('Hello World', 'hello', 'hi') -> 'hi World' - replace_ignore_case('Spam spam SPAM', 'spam', 'eggs') -> 'eggs eggs eggs'

Task

Implement replace_ignore_case(s, old, new) to replace all case-insensitive occurrences of old in s with new (non-overlapping).

Examples

Case-insensitive replacement

Input

replace_ignore_case("FooBarfoo", "foo", "x")

Output

xBarx

Both 'Foo' and 'foo' are replaced with 'x'.

Input format

Three strings: s, old, new passed as replace_ignore_case(s, old, new).

Output format

Return a single string with all case-insensitive replacements applied (non-overlapping).

Constraints

- 0 <= len(s), len(old), len(new) <= 5000 - If old is empty, return s unchanged - Matching is case-insensitive, replacement uses new verbatim

Samples

Sample 1

Input

replace_ignore_case("Spam spam SPAM", "spam", "eggs")

Output

eggs eggs eggs

All three case variants of 'spam' are replaced by 'eggs'.