10.censor


#1


Why my code doesn't work? Please help me !

def censor(text,word):
    l = text.split()
    for w in l:
        if w == word:
            w = "*" * len(word)
    result = " ".join(l)
    return result

print censor("hey hey hey","hey")

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


#2

You didn't split it at anything. You must put something in between the brackets for split.


#3

@bruce_wiseman, the text does get splitted into a list:

def censor(text,word):
    l = text.split()
    print l
    for w in l:
        if w == word:
            w = "*" * len(word)
    result = " ".join(l)
    return result

print censor("hey hey hey","hey")

#4

here, you update w:

w = "*" * len(word)

however, w only exist inside the loop. The moment your loop is finished, w cease to exist, so this update won't persist. I suggest you make a list result, and append the the asterix like you did here:

"*" * len(word)

or append the text uncensored if it doesn't match word. Or you could rethink your approach yourself, you don't have to follow my suggestions


#6

Thanks for your reply!


#7

You don't actually have to. It defaults to whitespace if you don't.