10 . Censor


#1

def censor(text, word):
---num = len(word)
---text = text.split(" ")
---new = [""]
---for x in text:
------if x == word:
---------new += ((num * "*") + " ")
------else:
---------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?


#2

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 * "*"]
      else:
         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]

#3

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


#4

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!


#5

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...


#6

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))

:slight_smile:


#7

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