You are building a chat filter for a messaging application. Given a string message and a list of strings banned_words, return a new string where every occurrence of any banned word in message is replaced with asterisks (*) of the same length.
The matching is case-insensitive for detection, but the original casing and structure of message (including spaces) must be preserved for all non-banned characters. A banned word can appear anywhere in message, including as a substring of a larger word, and all overlapping and non-overlapping occurrences must be censored.
If a character belongs to any banned word occurrence, replace it with *. Otherwise, keep it unchanged.
Function Signature
def filter_message(message: str, banned_words: list[str]) -> str:
Rules
-
A banned word matches a substring of
message
when the two are equal after lowercasing both.
-
Occurrences may overlap each other, and an occurrence of one banned word may overlap an occurrence of another. Every character covered by at least one occurrence becomes
*
.
-
Banned words contain only letters, so an occurrence never covers a space.
-
The output has the same length as
message
. Characters outside every occurrence keep their original case.
Constraints
-
1 <= len(message) <= 10^4
-
1 <= len(banned_words) <= 100
-
1 <= len(banned_words[i]) <= 50
-
message
consists of English letters (uppercase or lowercase) and spaces.
-
banned_words[i]
consists of lowercase English letters only.
Examples
Input: message = "hello world this is a test", banned_words = ["world", "test"]
Output: "hello ***** this is a ****"
"world" starts at index 6 and "test" starts at index 22. Each is replaced with asterisks of the same length, and everything else is unchanged.
Input: message = "the quick brown fox", banned_words = ["cat", "dog"]
Output: "the quick brown fox"
Neither "cat" nor "dog" appears in the message, so it is returned unchanged.
Input: message = "Banana Bandana", banned_words = ["ana"]
Output: "B***** Band***"
After lowercasing, "ana" occurs at indices 1 and 3 (overlapping, covering indices 1 to 5) and at index 11 inside "bandana" (covering 11 to 13). The uncovered letters keep their case, so the capital Bs stay.