What's wrong with my logic?


#1



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

Oops, try again. 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.


def censor(text,word):
    l=len(word)
    a="*" * l
    text=text.split()
    for i in text:
        if i==word:
            text[i]=a
    return "".join(text)
    #return text
    
censor("my name is pythonist","pythonist")


#2

When you do

for i in text:

'i' will refer to a string. You then do

text[i]=a

which doesn't make sense. Just as the error message say "list indices must be integers, not str".


#3

Your problem is with using list referencing incorrectly. You are using an item in a list as its index which is described in the error. The right way to do it is below:

for index, item in enumerate(text):
    if item == word:
        text[index] = a

#4

Thanks codeninja84962 & allentv.

Modified my code like below,

def censor(text,word):
l=len(word)
a="*" * l
text=text.split()
for index,item in enumerate(text):
if item==word:
text[index]=a
return "".join(text)
#return text

censor("my name is pythonist","pythonist")

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

I knew other logic of using replace function to solve this program but I don't wish to proceed further without fixing/understanding this, Please help me out to fix this.


#5

Its just a matter of space, fixed it.

Thanks folks :slight_smile:


#6

is a 'close the door' phrase, imho. There are lots of 'right ways' and accepting only one is an arbitrary closing of the door to further investigation, experimentation, exploration, &c.

This track is really about new learners stretching their wings and devising solutions to problems, drawing on what they've learned so far.. It doesn't mean much just having the 'right way' dropped on them if they haven't given due diligence to solving the problem for themselves, before refactoring upon further study of their own code.

I'm not critical of answers given with annotation, as long as they are not posed as the de facto solution, even if they are.