Censor: not censoring every instance



The code only seems to censor the first instance of the censor-needed word. For example: censor('hey hey hey', 'hey') only returns '*** hey hey' instead of '*** *** ***'.

I can't exactly get my head wrapped around this -- could someone more knowledgeable explain this to me? I have a hunch that after each loop, after words[x] = ast, the newly modified words list is not saved, and thus the code just censors the first "hey" three times.

def censor(text, word):
    ast = '*' * len(word)
    words = text.split()
    for w in words:
        x = words.index(w)
        if w == word:
            words[x] = ast
        return " ".join(words)


Too much indentation. Back it off four spaces so that the loop can finish iterating.


Hah! I make this mistake 9/10 times, yet never learn. Thank you for the help. :slight_smile: