Censor: Function not found


I keep receiving the following error. Can you spot my mistake in defining my function?
Oops, try again. Did you create a function called censor? Your code threw a "global name 'censor' is not defined" error.

def censor(text, word):
    txt = text.split()
    txt_list = []
    for each in txt:
        print txt_list
        if each == word:
            txt_list(each) = "*" * len(each)
    fin_txt = " ".join(txt_list)
    return fin_txt


I imagine that Python has something to say about your syntax, have a look at that error message instead.


Yeah I noticed the brackets on line 8 right after I posted. Thanks, now I'm getting a different error but going to see if I can fix it before I ask for further help.


So my code is running but not returning what I would expect. I put in some print commands so I could better see where the disconnect is happening. Below is the code followed by the output.

def censor(text,word):
    txt = text.split()
    for each in txt:
        if each == word:
            each = "*" * len(word)
            print each
            print txt
    txt2 = " ".join(txt)
    return txt2

print censor("I love my puppy Poop","puppy")


['I', 'love', 'my', 'puppy', 'poop']
I love my puppy poop

I feel the problem is:

each = "*" * len(word)

But I don't really understand why.
Any advice?


each is just a variable, it isn't part of the list, assigning to it has no effect on the list.


So I have to use:

for i in range(0, len(txt)):
     if txt[i] == word:



That's one way of going about it. You can leave out the 0 though.

I'd prefer to create a new list because that avoids dealing with indexes and it doesn't take any more time (same amount of operations anyway)

And I'd suggest more improvements but it's a slippery slope ending up at just using the replace function to do it all, which makes this exercise a little problematic - which tools are cheating and which are not?


There's also enumerate which provides both the value and the index

for i, word in enumerate(split_text):

iterating through enumerate produces tuples, those can be unpacked into more than one variable

a, b = [3, 2]

lists can be unpacked the same way (I used list for the above)

And on the path of that slippery slope, you can split on the word to censor, and join on asterixes.. you're already using those functions, so it's really just a matter of removing code. Is that cheating? .. problematic exercise.


I don't understand what
for i, word in enumerate(split_text):

is doing so it isn't something I would think of to use haha.


enumerate produces pairs, each pair gets assigned to i, word, which as can be seen on the other line, gets unpacked so that i gets the first value of the pair and word gets the second