Practice makes perfect: Censor; Why is this code incorrect?


#1

Not sure what I'm doing wrong here. What I assume to be the issue is that objects in a list cannot be replaced by reassignment using the variable said object was stored under in a for loop. Is this true? If so, would anyone happen to have a link to further information on the topic?

Note: I have already solved the exercise with another code, but I'm trying to understand why this one isn't working.


Like in the exercise, this function is supposed to take a string of text, and a word that is desired to be censored from said list


def censor(text, word):
    text = text.split(' ')
    for item in text:
        if item == word:
            item = '*' * len(word)
    return ' '.join(text)


#2

Change to item is not updated in text.

text[text.index(item)] = '*' * len(word)   # (corrected)

#3

Thought so. Thank you.

Is there any particular reason why that is, or is it kind of a "that's just how python works" kind of thing?


#4

item is not technically in the list, but a copy taken from the list. See my edit above.

text.index(item)

will return the index, which we can then use to replace the content at that index.

We can also use enumerate which has both index and item parameters.

for i, x in enumerate(text):
    if x == word:
        text[i] = ...

#6

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