This is the censor problem where we have to replace the 'word' in a 'text' with *s. My code is throwing a "list indices must be integers" error on line 5 of the code.

I was expecting that line 5 in the code checks if items in the list are equal to 'word'. If they are, they will be replaced with *s on line 6.

def censor(text, word):
    for i in text:
        if text[i] == word:
            text[i] = "*"*n
        print text


The error pops up because i refers to a character within text.
Try this instead:

def censor(text, word):
    words = text.split()
    for index, value in enumerate(words):
        if value == word:
            words[index] = "*" * len(word)
    return " ".join(words)

What enumerate does: python - What does enumerate mean? - Stack Overflow


Thank you very much!


The problem here is that text is an string and you need to specify a range ie. range(len(text)) instead of text in for loop so basically the code would look like
def censor(text, word):
for i in range(len(text)):
if text[i] == word:
text[i] = ""n
print " ".join(text )
Please mind the indentation


one question! Why do we need " " when joining "words"? Doesn't "text" have " "s in it already?


That's because we don't refer to text directly in the loop, we refer to texts, which is equal to text.split(). The split() function returns a list of each individual string in text, by removing all whitespace characters which include spaces and newlines to name a few. So, when outputting the text, we need to add spaces between each element.


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