I thought I could Censor like a WW2 mail worker


Hello. I'm having a spot of trouble with my censor. Mind helping me out?


Here's how I'm erring:
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***".

I don't understand why my code is not adding the "replacer" to the "new_word" I've created. I know the else statement adds the item by default after my replacing fails, just not why the "replacer" isn't replacing.

def censor(text, word):
    text = text.strip()
    text = text.split(',')
    new_word = ''
    replacer = ''
    for i in range(len(text)):
        replacer += '*'
    for item in text:
        if item == word:
            new_word = new_word + replacer
            new_word = new_word + item
    return new_word

Thanks for reading.


There may not be any commas in the text, but we can expect spaces, so that would be the character to split on.

    words = text.split(' ' )

Much simpler to spawn a list than a string of words. We can join them later.

    result = []
    for item in words:
        if item == word:
            result.append("*" * len(word))
    return " ".join(result)


Same logic, but variables (strings, lists) named a bit differently. May help some to compare and understand.

    def censor(text, word):
       censoredText = []
       textList = text.split(" ")

       for i in textList:
           if i == word:
               censoredText.append("*" * len(word))

       return " ".join(censoredText)