Strange output for censor program


#1

I'm getting really strange errors for this one. The code is as follows:
def censor(text,word):
for i in range(len(text)):
num=len(word)-1
if text[i]==word[0]:
count=1
while num>0:
if text[i+count]==word[count]:
count+=1
num-=1
else:
break
else:
for j in range(len(word)):
text=text.replace(text[i+j],'*')
return text

It shows this error: Your function fails on censor("Yo go fro yo go","go"). It returns "Y* * fr y* **" when it should return "Yo ** fro yo **".

I don't understand when I've specified if text[i]==word[0] how's this possible?


#2

@chipsurfer34929: Would you mind using

[code]#Your codee here[/code]


So we could see the indentation and where that last else refers to, please.


#3

Looks like this with indentation:

def censor(text,word):
   for i in range(len(text)):
      num=len(word)-1
      if text[i]==word[0]:
         count=1
         while num>0:
            if text[i+count]==word[count]:
               count+=1
               num-=1
            else:
               break
         else:
            for j in range(len(word)):
            text=text.replace(text[i+j],'*')
   return text

#4

@chipsurfer34929:
I understood that the code below is used to find the letters that we are supposed to censor.
The thing is: if we say we need to censor go, the code above will first find "g" to later find "o". But the problem is that value you're passing to replace is simply "o" but not "go".

           if text[i]==word[0]:
         count=1
         while num>0:
             if text[i+count]==word[count]:
                count+=1
                num-=1
             else:
                break
         else:
            for j in range(len(word)):
                text=text.replace(text[i+j],'*')

My suggestion is: you could find the length of the word you need to censor and work with it.
After that, go after those characters who form such word in your list. Start concatenating letters if the first thing you find is part of the word you need to censor, the first element of it [0].
Keep doing the step above until your new string's length is equal to your word's length.
After you got a new word generated by concatenating letters, check if that's equal to what you need to censor, if so go and censor that thing!
But if the new concatenated string is not equal to the word you need to censor, then go to the next element on text.

I hope my explanation was clear but if it wasn't, let me know and I'll find another way to explain!