Censor - Dont understand why code doesnt work


#1

Hi, this exercise requires me to:
Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.

The code I have is:

def censor(text, word):
  spl = text.split(" ")
  sen = []
  for x in spl:
    if x == word:
      sen += "*" * len(word)
   
    else:
      sen += x
      
  return "".join(sen)

When I print censor("hey hey hey","hey") the results shows ********* however, the error says "Your function fails on censor(“hey hey hey”,“hey”). It returns " " when it should return "** “.”

I can’t figure out what went wrong, would appreciate it if any of you could help me! Thanks!


#2

well, your function returns:

*********

for "hey hey hey" it should return:

*** *** ***

so something isn’t entirely correct with your solution, all the spaces between the words are gone, the error message isn’t entirely accurate displaying what your function actually returns, true. But your function need some improvement


#3

You might not actually mean what you wrote here

+= for list will append the elements in the value on the right

so for example

l = []
l += 'hello'

results in ['h', 'e', 'l', 'l', 'o'] because each element in 'hello' was appended to the array.

As a result, you’ve lost track of where words begin and end.

You need to keep that information, and use it to put everything back together again with spaces between the words


#4

Thanks for your feedback and hint! I thought about it and managed to get the code by appending instead of using +=


#6