10. Censor


What is wrong with my code?

def censor(text,word):
    for a in text.split():
        if a == word:
            for a in text:
                a = '*'
                return text   
            return text, word


a function ends the moment a return keyword is reached, which in your case is happen fairly quickly.

Here is what i would do, before the loop create a list. Append the words (censor when needed) to the list, then join and return the list.


Thank you! :slight_smile: :smiley_cat:


You got it to work with so little hints? Impressive. If not, post an updated version of your code so i can help you


def censor(text,word):
    text = text.lower()
    word = word.lower()
    tlist = text.split()
    for i in tlist:
        if i == word:
            i = '*'*len(word)
            tlist = "".join(i)
            tlist = "".join(i)
    return tlist

This is my code and is not working. It only prints the word replaced with the ***.


Sorry, I didn't paste the identations.


Mark your code and press the button in the editor to make formatting appear.


inside the function, create an empty list.

then, inside the if and else don't use join (which joins a list into a string) rather use .append() to append items to the list

Then just before the return join the list together

@turtwigpo posting answers without explanation is not according to the guidelines


"".join(i) will only result in a string containing i.

Try using append, but don't append to the same list you are iterating over.

You also shouldn't be changing the entire text to lower case. Instead use lower when comparing like this:

if i.lower() == word:

This way you can keep the original case.


def censor(text, word):
new = []
for i in text.split():
if i.lower() == word:
i = ""len(word)
new = " ".join(new)
return new

Thanks a lot, here it is :slight_smile: