Censor - need help!



Your function fails on censor("hey hey hey","hey"). It returns "*** *** *** " when it should return "*** *** ***".

def censor(text, word):
    split_text = text.split()
    new_string = ""
    for n in split_text:
        if n == word:
            n = "*" * len(word)
        new_string = new_string +  n + " "
    return new_string


I figured it out already. Thanks!


When we treat strings strictly as immutable objects, this method glides just under the radar (owing to the reassignment). You are not mutating the string, only replacing it each time. Fair enough.

There is a slightly purer way to do this, though. Using a list as the working object, then join it in the return value.

text = text.split()
result = []
for n in text:
    new_word = "*" * len(word) if n == word else word
return ' '.join(result)


Yes, this was the code I used in the end. Thanks a lot!


in the return add .strip() this cut the space from the beginning and the end of the string so its the good way


Thanks a lot! :grin: