Censor


#1

I'm having trouble understanding what's wrong with my code for the censor activity. The error I keep getting reads "list indices must be integers, not str."

Why can't I check if the user's desired word is equal to the word located in the list at index i?


def censor(text, word):
    text = list(text.split())
    for i in text:
        if word == text[i]:
            text[i] = "*" * (len(word))
    return " ".join(text)
    
text = raw_input("Enter your text: ")
word = raw_input("Enter your word: ")

censor(text, word)


#2

Yes, they need to be integers, not string.Do this:

def censor(text,word):
    text=text.replace(word,'*' * len(word))
    return text
print censor("We are here", "yes")

Hope this helps!? :smiley:


#3

yeah its works very well thank you so much !!!!


#4

You're welcome!

Keep on! Have fun coding! :smiley:


#5

Thanks for the reply! I understand why your code works, but why doesn't mine?

More specifically, I'm trying to cycle through each list item (for i in text). Then, I'm seeing if the user's word is equal to the list item at index i. Why can't I do this? (I think this is where the error is; I'm not sure. What needs to be an integer?)


#6

Okay. In an array, its position starts from zero.

For instance, I have a list say: Lab = ["chemistry", "biology", "physics"]

print Lab[1] would mean "biology". So you see the position in the array is a number(integer) not otherwise.

But when you loop for i in Lab, you get an error because you've said Lab["chemistry"] which doesn't make sense to the interpreter.

Hope this helps! :smile:


#7

Whoops, I thought I was looping through the positions in the list with "i" instead of the actual words in the list. Is there any way to loop through the positions/indices?


#8

Err... How about this? I commented out your for loop.

i = 0
def censor(text, word):
    text = list(text.split())
    # for i in text:
    if word == text[i]:
        text[i] = "*" * (len(word))
	return " ".join(text)
    
text = raw_input("Enter your text: ")
word = raw_input("Enter your word: ")

print censor(text, word)

#9

That works if I change the code around a little and increment i by 1 with a loop; thanks so much, didn't even think of that!

I also just came up with this, and it also works:

def censor(text, word):
    text = list(text.split())
    for index, i in enumerate(text):
        if word == i:
            text[index] = "*" * (len(word))
    return " ".join(text)
    
text = raw_input("Enter your text: ")
word = raw_input("Enter your word: ")

censor(text, word)

#10

Awesome! Nice thought there.

I just learnt also. :smile:

Have fun coding.