10. Censor: Struggling with the logic to add a space to the string in the right place



I can alter my code to either add a space at the start of every censored word or at the end, or a space before or after any words that aren't censored. Can I iterate through my list1 with the same range(len) I use later on to check if the word I'm iterating over is at the start or end of the list? If so, I could then add a space at the start of every word but the first to pass, as at the moment my error is returned as "*** *** *** " or "*** *** ***" instead of "*** *** ***".

def censor(text, word):
    list1 = text.split()
    empty = ""
    for a in list1:
        if a != word:
            empty += " " + str(a) 
            for i in range(0, 1):
                empty += " *"
            for i in range(1, len(a)):
                empty += "*"
    return empty


you could simply use a slice to overcome this problem? either empty[1:] or empty[:-1] depending on if the additional space is at the end or beginning. Slices are already covered, right?


Thanks! They had been covered, but I'd forgotten about them and couldn't find them easily with CodeAcademy's new layout. Works perfectly.


hi people,

Could you tell me please why codeacademy doesn't like my code. It actually brings the required output. The error is:
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns " *** *** " when it should return " *** ***".
The code is:

def censor(text, word):
    l=text.split(" ")
    for i in l:

        if i==word:
            k=k+" "+i
            k=k+" "+i
    return k
    print k
print censor("hey bay hey", "hey")


you have the exact same problem:


i replaced the spaces with underscores so you can see it, but as you can see, you need to slice of the space in the beginning as well.