Censor error


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/censor-?action=lesson_resume

I am getting the following error message:
Your function fails on censor(“hey hey hey”,“hey”). It returns “*********” when it should return “*** *** ***”.

I am guessing it has something to do with spaces between the words, how can I fix this?

Here is my code:

def censor(text,word):
  length=len(word)
  splt=text.split()
  new_word=""
  censor="*"*length
  for i in splt:
    if i==word:
      new_word+=censor
    else:
      new_word+=i
  return "".join(new_word)

Thanks in advance!


#2

Hi @caitlingm7,

You are starting with an empty string …

  new_word=""

Instead, start with an empty list

  new_word=[]

Then you can use append to accumulate the words …

  new_word.append(censor)

… and …

    new_word.append(i)

Here, you are calling join from an empty string …

  return "".join(new_word)

Therefore, there will be no spaces between the words in the result.


#4

Thank you! I did this and it worked.

def censor(text,word):
  length=len(word)
  splt=text.split()
  new_word=[]
  censor="*"*length
  for i in splt:
    if i==word:
      new_word.append(censor)
    else:
      new_word.append(i)
  return " ".join(new_word)

#5