How can I use split( ) to make censor?


Why doesn’t this work?

def censor(text, word):
  new_text = []
  text = text.split()
  print text
  for i in text:
    if i == word:
      new_text = new_text.append("*" * len(word))
      new_text = new_text.append(i)
  new_text = " ".join(new_text)
  return new_text


It looks like it should work. Is it not being accepted by the lesson checker? If not, then perhaps try it with the print statement removed.


You should probably examine what makes you say that it doesn’t work - you need to know what the difference in behaviour is before you can start looking for its reason. After that think about what should happen and start comparing with what does happen. Printing out messages/information from your function allows you to observe what’s going on.


I tried using the ‘range’ function instead of the ‘count’ variable and I’m not sure why it’s not working. It just prints out the full sentence without any censorship:

def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    for i in range(0, len(words)):
        if i == word:
          words[i] = stars
    result =' '.join(words)

    return result
print censor("this hack is wack hack", "hack")


There could be a number of reasons for this. The most obvious one would be to check if the comparison:

if i == word:
   print "i get here"

oops, that doesn’t seem to happen. Lets check the value for comparisons:

for i in range(0, len(words)):
   print i, word

that explains a lot.

its important to teach yourself these thinking and debug steps. Of course a debug tool would be better.


Apologies - I don’t understand this


i showed you print statements, which you can include in your code to help you identify the issue.

what do you not understand? Please be more specific.


Ah okay,

So you are checking if the ‘if’ statement and ‘for’ loop is functioning properly, correct?


yes, that is step 1:

if i == word:
   print "i get here"

which lead me to the conclusion that the if condition isn’t functioning properly, given word is present in text.

so then i am checking why the if condition is not working properly:

for i in range(0, len(words)):
   print i, word