Censor Issue


#1
def censor(text, word):
  word_list = text.split()
  new_word_list = []
  for w in word_list:
    if w == word:
      new_word_list.append('*' * len(w))
    else:
      new_word_list.append(word)
  return " ".join(new_word_list)

I’m sure I’m doing something really simple wrong but I just can’t spot it. My code just returns the original text so I assume that nothing is triggering my initial if statement but I’m not sure why. I would be grateful for any help. Thank you

EDITED TO SHOW CORRECT CODE BELOW

def censor(text, word):
  word_list = text.split()
  new_word_list = []
  for w in word_list:
    if w == word:
      new_word_list.append('*' * len(w))
    else:
      new_word_list.append(w)
  return " ".join(new_word_list)

#2

you had:

return " ".join(word_list)

And then you made an edit:

return " ".join(new_word_list)

that is quite a difference.


#3

yes, I realised that I was joining the wrong list so now I’ve broken it more…
I was just looking if I could delete my post until I could figure out what I need to ask. First time posting so I’m learning as I go.


#4

look at this line:

new_word_list.append(word)

(its from the else clause), what are you appending to new_word_list here and why?


#5

ah of course should be w not word!!
I knew it would be something small, just couldn’t see it.

Thank you very much it works perfectly now


#6

adding a function call and print statements can help to find issues like these.

You’re welcome :slight_smile:


#7

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