Censor not censoring


#1



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

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

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')


#2

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.


#3

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.remove(word)
            lst.insert(loc, "*" * len(word))
            newLst = " ".join(lst)

    return newLst

#4

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


#5

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

Nevermind. Found my answer.


#6

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?


#7

You can also use this code:

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


#8

Can someone tell me why we have to split text?


#9

#10

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?