10 . Censor


def censor(text, word):
---num = len(word)
---text = text.split(" ")
---new = [""]
---for x in text:
------if x == word:
---------new += ((num * "*") + " ")
---------new += (x + " ")
---return "".join(new)

Not returning appropriate response for "hey hey hey, hey" error. I know it's because I'm adding an extra space at the end of the word, so if the word comes at the end of a string, it prints an extra space and errors. Any ideas for how to tackle this without using strip?


You can simply not add the spaces and then use " " as a separator for the join method. To do so, you have to work on list of words, not list of characters:

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

But I don't really understand why you don't want to use slicing, it's pretty neat:

return "".join(new)[:-1]


Thanks for the explanation! I do think slicing is cool - but seems like it wouldn't work in every scenario :slight_smile:


Oh, I see, for me, it just feels more natural to treat the sentence as a list of words so I also prefer the solution without slicing :slight_smile: You're very welcome!


My problem has always been how to best approach these sorts of problems - I find that I usually look at it from too broad or narrow a scope (how I treated it as characters and not a list of words, and similarly doing the opposite in a flipped scenario). I figure that's more just pattern recognition over time probably...


I figure that's more just pattern recognition over time probably...

I am sure of that. Few months and you will probably start writing something like this:

def censor(text, word):
    return ('*' * len(word)).join(text.split(word))



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