[Need help! ] Censor, where is the problem?


#1



Error message:
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***".


I think the line 6 would be the problem but I am not sure and I also have no idea how to rewrite.
Thanks!


def censor(text,word):
    list1 = text.split()
    stars = ("*" * len(word))
    for indices in list1:
        if indices == word:
            indices = stars
    new_text = " ".join(list1)
    return new_text

print censor("this hack is wack hack", "hack")


#2

indices are read-only values from the list, you can't use them to manipulate list1, for this you need indexes (range() can give you those)


#3

@stetim94 Hi, why can't I use the indices? I just want to use the indices to check whether any item in list1 is equal to word and then replace it. I am really confused now. Can you explain more clearly?
Thanks!


#4

you can, but given indices contains read only values from the list, any changes made to it won't persist once the loop has finished running. list1 still contains the list as it was before the loop


#5

@stetim94 Hi, I think I get some feeling about this though I don't understand clearly. Thanks!


#6

well, you will need to modify list1 to make the change persist after the loop

to update elements in lists, we need indexes

which range() can provide us

once we have the indexes, we can replace a word which need censoring in list1 list


#7

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