Censor "Your function fails, It returns "*** *** *** " when it should return "*** *** ***"


#1

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

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

I've tested this on other input variants, it works just how it should work. Input - string, output - correcrly censored string.

def censor(text, word):
    word_censored = '*' * len(word)
    listOfWords = text.split()
    textCensored = ""
    for w in listOfWords:
        if w != word:
            textCensored += (w + ' ')
        else:
            textCensored += (word_censored + ' ')
    return textCensored

#2

If you look closely the error is saying that your output includes an extra space after the censored words,

"*** *** *** "

instead of,

"*** *** ***"

That is what is causing the error. :slight_smile:


#3

Oh, that's embarasing
Thank you!


#4

Haha it's the little mistakes that really cost us most of the time. :smile:

You're welcome


#5

May I ask how you fixed it?


#6

Sure
I used list for output, not string (see first post), and used join() method.

def censor(text, word):
    wordCensored = '*' * len(word)
    listOfWords = text.split()
    textCensored = []
    for w in listOfWords:
        if w == word:
            textCensored.append(wordCensored)
        else:
            textCensored.append(w)
    return " ".join(textCensored)

Censor spacing error
#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.