Censor - need help!


#1



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

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


#2

I figured it out already. Thanks!


#3

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
    result.append(new_word)
return ' '.join(result)

#4

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


#5

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


#6

Thanks a lot! :grin:


#7