Censor


#1



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

Error: Does your censor function take exactly two arguments, a text string and a word to replace with asterisks? Your code threw a "list indices must be integers, not str" error.

i don't understand what i'm doing wrong, i went with the hint trying the .split/.join that were never taught, googled them and this is what i found,

def censor(text,word):
    
    ast = "*" * len(word)
    text_words = str.split(text)

    for char in text_words:
        if char == word:
            text_words[char] = ast
    text_words = " ".join(text_words)

    print text_words
    return text_words


#2

Call your function yourself to get the line number printed out, and then look closer at that line and re-consider what's happening there.
You may want to add print statements to check what any names you're using on that line are refering to if you're not certain. The error message already states that you're trying to use a string as if it was an index, and that the value being indexed is a list. It also says that the index must be int. So, just look at that line and ask yourself what you're trying to do and how that's supposed to be accomplished. And again, use print statements to figure out what things contain if you are unsure.


#3

i don't understand why what i did is considered wrong, sure that's what the error says but why? from what i was taught so far is that

for char in text_words:
if char == word:
text_words[char] = ast

should just replace the element text_words["element"] = " * ... * "

it should not matter if the element is string or int
i've seen
list[int] = stuff
list["string"] = "string"
int = "string"
list[int] = stuff

it shouldn't matter


#4

Clearly it doesn't, so find out what it does instead, right? Use print statements for that. Start by finding out what each name at the line of the error, refers to. Then ask yourself if you can do the action that you're doing at that line, with those values. And read the error message, because that has something to say about exactly that, right?

What do you think this does?

print 'hello'['kebab']

Try it.
What's the result? Compare what happens with what is going on in your code. Read the error message. How does the error message relate to what is wrong with that code above?


#5

ionatan, great learning from you, thanks :slight_smile:


#6

I liked what ionatan has mentioned about debugging the code and finding your way out. But just to give you a little hint, you can make use of enumerator function to get index of an item.

    for index, item in enumerate(list_name):
        print index, item

#7

def censor(text,word):
length=len(word)
mul=""length
print mul
words=text.split()
for i in words:
if i == word:
text=text.replace(i,mul)
return text
print censor("hi da macha","da")

check out this