Censor


#1




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


I dont understand why the first "hey" isnt censored but the rest are


def censor(text,word):
    word_list = text.split()
    for item in word_list:
        if item == word:
            word_list.remove(word)
            word_list.append("*" * len(word))
    return " ".join(word_list)
    
print censor("hey hey hey","hey")


#2

If you want to iterate over word_list using a for-each, you cannot modify it in that loop; the indexing gets thrown off, so the for-each starts ignoring some elements in the list

(well technically in some cases it's fine including maybe yours. But what's also wrong here is:
-The remove() removes from first found location in text, but
-The append() always adds to end)

something which might make this easy: Python has str.replace()


#3

append = insert at the end of the list.

we can walk over what happens, the loop makes 3 iterations, so we start with:

["hey", "hey", "hey"]

okay, so then you remove the first one (index 0) and append it to the end:

["hey", "hey", "***"]

okay, so now the for loop moves on to index 1, removes the item and appends it to the list:

["hey", "***", "***"]

okay, so now the loop arrives at index 3, which contains ***, so the if condition evaluates to false.

The exercise is also going to test other strings like:

censor("this hack is wack hack", "hack")

this would mean you change the order of the words, you can't do this.

without using to much built in function, you have two options to make this program work:

use range(), this will give you indexes which means you can replace items in your list, or built an if/else, the if should append censored words to an empty list and else should append words that don't require censoring.


#4

Thank you so much for your reply. I understand where I went wrong now. Both you and trigonometrical helped a lot :slight_smile:


#5

glad we could help :slight_smile: please tell me you didn't use the built in string.replace() method, it is kind of boring. Building your own function is so much more fun to do :slight_smile: and better for improving your coding skills


#6

I actually did use it but now I'll try and build my own function. Thanks so much :slight_smile:


#7

okay, good luck building your own function, i provided some clues on how to do that:

If you need more help with censor, you can reply to this topic


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.