Censor - getting an error message that I've gotten it right? :S


#1



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


Isn't that what I'm supposed to get? Why do I get an error? It exists regardless of whether I comment out the join function or not.


def censor(text, word):
    words = text.split()
    censored_word = ""
    for string in words:
        if string == word:
            censored_word += "*"*len(word) + " "
        else:
            censored_word += string + " "
            
    #why is the next line important?        
    #" ".join(censored_word)
    return censored_word
    
print censor("hey hey hey","hey")


#2

You have a trailing space in your result that the SCT is not accepting.


#3

But if I don't add it it won't accept it - or is that what the join function is there for?


#4

If we have a list of words, then join can be given a space character as the separator. It won't add any leading or trailing spaces to the finished string.

You could also return a slice of your string that does not have the last character.

>>> string = "hey hey hey "
>>> string[:-1]
'hey hey hey'
>>>

#5

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

That happens when I do the following

def censor(text, word):
    words = text.split()
    censored_word = ""
    for string in words:
        if string == word:
            censored_word += "*"*len(word)
        else:
            censored_word += string
                
    " ".join(censored_word)
    return censored_word
    
print censor("hey hey hey","hey")

Why doesn't the join function work here? It doesn't seem to be adding a separator between the words at all...


#6

>>> " ".join("this is some text")
't h i s   i s   s o m e   t e x t'
>>>

I don't think you want that to happen. As it stands that line is affecting nothing.

Your earlier code just needed a modified return value, according to the hint I gave you earlier.

return censored_text[:-1]

That will chop that last space off. Your code worked fine, otherwise.


#7

Oh ok, I see. It's just that the lesson implied that I should use join somewhere, but I guess it's not vital!

But thanks, that did it! :slight_smile:


#8

If that is the case, then yes, it should be used. This implies a list.

 results = []
 results.append( "*" ... )
 results.append(n)
 return " ".join(results)

You'll figure where to put those lines (the right code)


#10