Censor


#1




Why doesn't my code replace/recognize the "hey"s?


def censor(text, word):
    split_list = text.split()
    for string in split_list:
        if string == word:
            string == "*" * len(word)
    return " ".join(split_list)


10: Censor
#2

string is your iterator, its gets assigned each word in split_list.

so string won't persist, it only exist inside the for loop. Make a list or string outside the for loop where you can append (un)censored word to


#3

Thanks! Just wondering, is there any way to make "string" (the iterator) recognize and change the word it's referring to in the split_list outside of the for loop?


#4

no. There are two things you can do:

create an empty list before the loop, loop over split_list and append to the empty list, use if/else to check if the word need censoring, if so, append asterixs to the empty list else append the word.

The other thing you can do use range(), this will give you indexes so you can substitute words which requires censoring in split_list


#5

Gotcha. I used the first method as you advised earlier, thanks for the help!


#6

Note that when we write a look-up loop like the above, we may not mutate the iterator. That is, we cannot change it to something else.

To change a list element inside a loop, we need to use the index. There are a number of ways to do this. index(), iterate a range(), or enumerate() the object so both value and index are exposed.


#7

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