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


#1



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


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) 
        else:
            for i in range(0, 1):
                empty += " *"
            for i in range(1, len(a)):
                empty += "*"
    return empty


#2

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?


#3

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


#4

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(" ")
    m="*"*len(word)
    k=""
    for i in l:

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

#5

you have the exact same problem:

_***_bay_***

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.


#6