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

def censor(text, word):
    for s in intext:
        if word==s:
    return " ".join(intext)


I have also tried with text.replace(word,star) in a while loop. It returns None. if anyone has suggestions using .replace( ), please feel free to let me. I would love to know what I had it wrong there as well.


Let me show you a better example of the error:

censor("a b c", "b")
=> "a c ****"

There are two main problems in your code:

  1. Why exactly four stars (star="*"*4)? Number of stars should depend on the length of the word.
  2. intext.append(star) appends stars to the end of intext, even if the s is in the middle.


This should be set to len(word) not a literal. The program doesn't know how long the word is until it sees it.

This is an item lookup loop, and as such we cannot mutate (alter) the iterable.

To get around this, use an indexing loop, instead.

for s in range(len(intext)):
    if intext[s] == word:
        intext[s] = star
return ' '.join(intext)


Thanks! I was totally not paying any attentions on my star variable, and thanks for clearing my misunderstanding on .append( ).


Thanks for the example of indexing loop!


You are very welcome!


Your code compares only 1 character to an entire word, your condition inside your loop will never be fullfilled.


The idea at this point is not worry about efficiency. That function has not been introduced at this stage for most people, and not encouraged in this exercise, even if it does work.


According to this page, this loop can be rewritten using enumerate().

I came up with this (functional) result:

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

Or, manually, but not as python-y:

def censor(text, word):
    words = text.split()
    index = 0
    for i in words:
        if i == word:
            words[index] = "*" * len(word)
        index += 1
    return " ".join(words)


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