Censor not censoring


I can't tell what am doing wrong in this.


Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "h e y h e y h e y" when it should return "*** *** ***".

Why is it not replacing th word?

def censor(text, word):
    text_word = str.split(text)
    for index, n in enumerate(text_word):
        if n == word:
            text_word = text.replace(n, '*' * len(word))
        text_word = ' '.join(text)       
        return text_word
censor('what the fuck is wrong with you', 'fuck')


Your function is really just doing this:

def censor(text, word):
    return ' '.join(text)

All the rest you're just discarding one way or another.

I suggest using print statements to have your function explain what it does(n't) so that you can tell where it goes wrong.


This has worked for me:

def censor(text, word):
    lst = text.split()
    for i in lst:
        if word in lst:
            loc = lst.index(word)
            lst.insert(loc, "*" * len(word))
            newLst = " ".join(lst)

    return newLst


thanks, your answer helped me finally finish, i was trying to remove and insert but couldnt index correctly. thank you


Call me stupid, but when did we learn remove and insert?`

Nevermind. Found my answer.


However, I would like to ask why you choose the variable and list names you do. Why "newLst" and not "new_list" so it's clearer to others reading your code?


You can also use this code:

def censor(text,word):
return text.replace(word, " * " * len(word))


Can someone tell me why we have to split text?



This topic is really old, please make a new (linked) topic. see guidelines

We don't have to do anything, we can write solutions which do not involve split, although that is probably more difficult. You did check python documentation to see what .split() does?