I thought I could Censor like a WW2 mail worker


#1

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

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096

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
        else:
            new_word = new_word + item
    return new_word

Thanks for reading.


#2

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))
        else:
            result.append(item)
    return " ".join(result)

#3

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))
           else:
               censoredText.append(i)

       return " ".join(censoredText)