Censor


#1

I do not understand why I cannot use the code in line 6. What would be the correct way to do it instead?

def censor(text,word):
    word_list = text.split()
    length = len(word)
    for i in word_list:
        if i == word:
            i = "*"*legth
    print word_list
    new_word = " ".join(word_list)
    return new_word

#2

This change will not take place. Also, check spelling.

When a variable is a look-up value, changes made to the value are discarded when the value is discarded. If we wish to change the actual value in the list, then we need to know the index so we can access the actual element in the list.


#3

Yes, I found that error afterwards.

Ok, I found that people use enumerate() for that, but couldn't understand why. I did not know that it gets discarded. Is there an explanation why it gets discarded other than "that is how it works"? I mean, it would be useful to be able to do this.
Just trying to understand how things work


#4

the_list = [3, 5, 8, 13, 21]

# the look-up loop

for item in the_list:
    #

In each iteration, item will be one of the values in the list. We can do something with that value, inspect it, compute with it, etc. but we cannot change the list by changing that variable in the loop. As the loop is concerned, that item has been read from the list, and it moves on to the next item. That is what I mean by discarded. It is transient and replaced with the next item.


#5

Ok, I think I got it! Thank you very much!!!


#6

enumerate is a handy function since it both looks up an item, and tracks its index. If we did not have this function, we could still use the look-up loop (as opposed to a range loop) by using the built in index function.

list.index(item)

will give us the index of the current item. I believe this will also work for tuples which keep their order. It would not make sense to expect it to work on sets since they do not have an order.


#7

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