Censor


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/4

def censor(text,word):
    a = text.split()
    for m in a:
        if m == word:
            m = "*" * len(word)
        print m ,    
censor("hey hey hey","hey")

What's wrong with my code above? I run the code ,the results is "*** *** " indeed. But it prompted that the"Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "None" when it should return " *** ***"."
Who can help me? Thanks!


#2

you need to return something in a function, instead of print.


#3

Line 1 no flag
Line 2 no flag; could be more explicit
Line 3 no flag
Line 4 Flag: reassignment of iterator variable

This is where things break down The iterator variable is a key, and as such is immutable. This code simply tosses that aside and gives a new value. Now the iterator is in a tumble since it no longer references a valid key.

Better that we assign words to a result, than manipulate the data object (or the iterator variable), itself. That way we can reproduce the result later, if needs be.

def censor(text,word):
    a = text.split()
    r = []
    for m in a:
        if m == word:
            r.append("*" * len(word))
        else:
            r.append(m)
    return " ".join(r)    

print(censor("this hack is wack hack", "hack"))
this **** is wack ****
None

#4

Tossing in this extra study concept: List comprehension and Python ternary rolled into one:

def censor(text,word):
    a = text.split()
    return " ".join(["*" * len(word) if m == word else m for m in a])

#5

thanks, it works now


#6

yes, you're right. I have corrected it! Thanks~


#7

I used the built-in string method .replace(old,new) in my code. I copy and pasted my code below. I hope this helps.

def censor(text,word):
censor = len(word)''
new_text = text.replace(word,censor)
return new_text

print censor("this hack is wack hack", "hack")