10/15 censor (partial censoring?)


#1

This solution passed as correct, but I’m not sure that it’s quite right. At least, I’d like it to be better.

def censor(text, word):
  strList = text.split()
  redact = []
  for i in strList:
    if word in i:
      i = "*" * len(word)
    redact.append(i)
  redacted = " ".join(redact)
  print redacted
  return redacted

censor("just testing to test it", "test")

The above block returns: “just **** to **** it.” Whereas, I want to return “just ***ing to *** it

Changing line 5 to:

    if i in word:

Returns: “just testing to **** it

I think this is better than my first solution. But not sure that either of them are quite right?


#2

Hi @toprank,

For the censor exercise, individual words are considered to be the portions of text that are delimited by whitespace. That is why the following statement is ideal for this task, and is suggested by the hint …

  strList = text.split()

Your censor function should replace, with asterisks, only entire words that match the value of word exactly, despite the fact that the instructions are not quite clear about that. For this purpose, use the == operator instead of the in operator for the if condition.


#3

Thanks, @appylpye. So this exercise didn’t expect an input like this:

censor("I was hacked by the hacker who was hacking just for fun", "hack")

to return:

“I was ****ed by the ****er who was ****ing just for fun”

Is your suggestion of:

if word == i:

more Pythonic than:

if i in word:

Both lines replace, with asterisks, only entire words that match the value of word exactly.


#4

If you use …

  if i in word:

… then this …

censor("the hacker created a hack", "hacker")

… would return

the ****** created ****** ******

The source of the problem is that "a" is in "hacker", and so is "hack".

The == operator will check for exact equivalence, so the output would be …

the ****** created a hack

#5

Sweet. Thanks @appylpye. I understand.

if i in word is cycling through the characters, which returns an incorrect result. Thanks.


#6