10/15 Help please!


#1

Hi, why it is not working?...

def censor(text, word):
    a = text.split()
    o = len(word) * '*'

    for i in a:
        if i == word:
            i = o
        
    return ' '.join(a)
    print ' '.join(a)
    
print censor ("hey hey hey", "hey")

#2

@happylol take a look at your code below with comments why it did not work

def censor(text, word):
    a = text.split()
    o = len(word) * '*'

    for i in a:
        if i == word:
            #changed this here
            #the original statement you had
            #did not work because it is just the
            #iterator that runs through the elements in the list
            #its value keeps changing so when you write
            #i = o
            #yes it will change i but it has nothing to do with
            #the list you want to modify
            #to make it work you have to get the element in the
            #the list itself
            a[a.index(i)] = o
        
    return ' '.join(a)
    #this print statement is UNREACHABLE
    #i.e. not executed
    print ' '.join(a)
    
print censor ("hey hey hey", "hey")

#3
for i in a:
    if i == word:
        i = o

I don't think Python will let us change i in a for..in statement.

def censor(text, word):
    a = text.split()
    o = len(word) * '*'

    for i in range(len(a)):
        if a[i] == word:
            a[i] = o
        
    return ' '.join(a)
    #print ' '.join(a)    # unreachable after return
    
print censor("hey hey hey", "hey")