10 - censor


#1

Hi, I'm not too sure why my code doesn't work, I've looked at a few other topics, but the error thrown is that I need to use integers in the comparative statements, but I don't understand how I can when a string of letters can't become an integer.

def censor(text, word):
asterisk = '*' * len(word)

words = text.split()

result = []
for i in words:
    if words[i] != word:
        result.append(words[i])

    else: 
        result.append(asterisk)

' '.join(result)

return result




cheers ~~


#2

the error is here. To explain the pit fall run this code and see what you get

countries = ["Canada","USA","Spain","Zambia", "Indonesia"]
for i in countries:
    print i

When you write this code

for i in word

the interpreter created an iterator over your elements(an iterator is an object that enables a programmer to traverse a container, particularly lists.). This iterator will have the same type as the elements in your list.

Now the elements in your iterable are string and at each iteration i(which is what you called your iterator) will be a string and this string will be the current element of the iteration.

Therefore to compare the current value of i to the target word , you can just do this

if i != word: #instead of word[i] which is invalid
    result.append(i)
#list objects can be accessed by indices(which must be integers) but i is not

Does this help?


#3

It does help, thank you very much!


#4

result = " ".join(result)


#5
def censor(text,word):
    asterisk = '*' * len(word)
    words = text.split()
    result = []
    for i in words:
        if i != word:
            result.append(i)
        else:
            result.append(asterisk)
    return " ".join(result)

    
here you go!

#6
def censor(text, word):
     return text.replace(word, '*'*len(word))