10. Censor


#1

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   
        else:
            return text, word

#2

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.


#3

Thank you! :slight_smile: :smiley_cat:


#4

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


#6

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)
        else:
            tlist = "".join(i)
    return tlist

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


#7

Sorry, I didn't paste the identations.


#8

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


#11

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


#13

"".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.


#14

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

Thanks a lot, here it is :slight_smile: