Censor lesson


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096#

My code somewhat works but fails on the first string in the list.

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


 
def censor(text,word):
    textfrag = text.split()
    for string in textfrag:
        if string == word:
            cenline = "*" * len(string)
            textfrag.remove(string)
            textfrag.append(cenline)
    newtext = " ".join(textfrag)
    return newtext


#2

remove causes index shifts, lets say i have the following code:

x=['a', 'b', 'c']

and i want to remove all of them from list, i can't do:

for i in x:
     x.remove(i)

because, the a at index 0 gets removed. But lists can't have empty indexes, so, everything to the right of where a used to be shifts to the left so we have left:

['b', 'c']

with b at index 0 and c at index 1

right, remove was successful, so loop moves on to the next index (1), causing b at index zero to be skipped

This is the same problem you are facing


#3

Thanks! I ended up figuring it out by having it print the indices and noticing it only registered two of them. It ends up working better by passing it into another empty list.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.