10/15 Censor


if my input string and censor word are as follow: this is a book,is
What is the expected result?

this ** a book


th** ** a book
I believe that it is supposed to be the first one. My code did the second version,yet I got correct answer !?


it should be the first one. This is known as a corner case, the test cases by the exercises do not cover this corner case. Its unfortunate, but its good you realize it :slight_smile:

Did you use .replace()? Using a built-in function doesn’t teach you to build your own algorithm, the point of the exercises is to learn


Thanks for your response :slight_smile:
Here is my original code:

def censor(text,word):
  if len(text) < len(word):
    return text
    pos = text.find(word)
    if not pos == -1:
      return text[0:pos]+"*"*len(word)+censor(text[pos+len(word):],word)
      return text

This is what I came up with after I sought a hint:

def censor(text,word):
  words = text.split()
  print words
  for i in range(len(words)):
    if words[i] == word:
      words[i] = "*" * len(word)
  return " ".join(words)

Still, I think that split will not work in case that there are more than one space bar between each word.


it will work:

print "hello    world".split()

given at each space between the words, a split is applied.


i’m sorry for my ambiguity.
i mean the step when we rejoin the result string won’t give exactly the same except for censored words if we use split.

let’s say here is the input(string,censored word):
this is my string,is— two spacebars between “this” and “is”

return “ “.join(result) will remove one space bar from the input string.

did i miss anything?


that is a corner case, in a normal sentence there is only one space between words. So yes, if you want to keep the spaces, you will have to make some changes


Did anybody else get this error message for this exercise?:

Your function fails on censor(“hey hey hey”,“hey”). It returns " *" when it should return " ".

By the looks of this test case… shouldn’t it all be censored?

Update: Ah sorry, I realise my mistake - you are supposed to sensor with the same number of asteriks as letters in the word!


def censor(text, word):
words = text.split()
result = '‘
stars = ‘*’ * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =’ '.join(words)

return result

I can’t understand how the if statement works. Please help me.


i will contain the words from words list (the for loop takes care of this), by comparing these words with the word you want to censor, you can verify which words need censoring and which not. if is responsible for this


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