Censor


#1



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


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):
    text=text.split()
    n=len(word)
    for i in text:
        if text[i] == word:
            text[i] = "*"*n
        print text


#2

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


#3

Thank you very much!


#4

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):
text=text.split()
n=len(word)
for i in range(len(text)):
if text[i] == word:
text[i] = ""n
print " ".join(text )
Please mind the indentation


#5

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


#6

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.


#7

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