10. censor


Hi guys, this is my first post to codecademy forum.

Result for my code is:
hey hey *** hey

For some reason the below code is replacing all the words other than the sensor word to asterisks. Can someone point out what mistake am i doing.

I instead expect it to show up output as:

*** *** oye ***

def censor(text, word):
    text = str(text.lower())
    word = str(word.lower())
    words = text.split()
    print str(words)
    for word in words:
        newtext = text.replace(word, "*"*len(word))
        return newtext
    print newtext    
text = raw_input("Input string: \n")
word = raw_input(" Input the word to be replaced \n")
print censor("hey hey oye hey", "hey")


What happens if text is not a string? Object has no attribute, lower. So it follows we need to first convert to a string then apply .lower() to that.

text = str(text).lower()

This introduces another problem,though. When we return the string it will not just be redacted, but mutated as well. Maybe changing case is not such a good idea. What if all we want is to remove street but not Street?

So in the end, making sure we have a string is a good measure, but changing case may not be.

That's not where the real problem is, though. In your for statement you are obliterating the parameter, word by declaring it as the iterator variable in your loop. Study it closely and see why you got the output you got.

The return statement inside the loop is never a good sign. It returns after only one iteration of the loop.

Something else to consider, as well. text.replace() is out of place in a loop. It can be applied to the entire string in one stroke.


text = "hey hey oye hey"
word = "hey"
text = text.replace(word, "*"*len(word))
print text     # *** *** oye ***

However, the objective of the lesson is, I believe, to solve this with a procedure rather than a built-in, for the practice.


A post was split to a new topic: Not work ..... hmmmm