Question on "censor" Exercise


#1



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

So I almost have this working right, but I can't get the final output to translate from a list to a string. I thought that that is what return "".join(final) does? It has worked for me before. What's wrong with ma code?

Btw, all the print statements are just so I can see what the code is doing at each step. It looks perfect until the very end.


Code:

def censor(text, word):
    split_text = text.split()
    final = []
    x = 0
    print x
    print final
    while x <= len(split_text):
        if word == split_text[x]:
            final.append("*" * len(word))
            x += 1
            print x
            print final
        else:
            final.append(split_text[x])
            x += 1
            print x
            print final
    else:
        return "".join(final)

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

Results:

0
[]
1
['this']
2
['this', '****']
3
['this', '****', 'is']
4
['this', '****', 'is', 'wack']
5
['this', '****', 'is', 'wack', '****']
Traceback (most recent call last):
  File "python", line 24, in <module>
  File "python", line 11, in censor
IndexError: list index out of range


#2

your while loop:

while x <= len(split_text):

use < instead, why? this hack is wack hack are 5 words agree? So length is 5, but they are indexed at: 0,1,2,3,4. so you don't want to include 5, which is why you need to use < instead of <=.

Also, you do want to have a space between the words, you need to do this in join:

" ".join

notice the space between the quotation marks (")


#3

Ok, that makes sense. And it works now. Thanks.