Can't solve why Censor is wrong


#1

I cant figure out why my code doesn't work:

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

Message: Oops, try again. Your code looks a bit off--it threw a "name 'word' is not defined" error. Check the Hint if you need help!
please tell me what is wrong


#2

I don't like this method, but this is quite difficult for me to explain it easy, so here you have my code

def censor(text,word):    
    tex = text.split()
    new_text=[]
    for t in tex:
        if t==word:            
            new_text.append("*"*len(t))
        else:
            new_text.append(t)
    return " ".join(new_text)

First of all you need to create new empty list, into which you will insert (append) words.
So this part

doesn't do anything. If i == word you append as many * as word is long to your empty list.

You also need else statement, because in your current code nothing happens with words which are different than check word. If they are different you just append them to new list.


#3

I used:

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

I think... It's a while ago.
Thanks for the quick reply by the way.


#4

Hi @husky02,

def censor(text,word):
    a=text.split()
    for i in a:
        if i==word:
            i="*"*len(word) # line X
    return " ".join(a)

Line X doesn't modify the corresponding element in the list a. You might want to have a look at map method, or use @dawidrz87 method.