Censor, returns "*** *** *** " when it should return "*** *** ***"


#1



Practice Makes Perfect: Censor


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


I don't know what I did wrong or what the problem is.


def censor(text, word):
    new = ''
    for i in text.split(' '):
        if i == word:
            i = '*' * len(word)
        new += i
        new += ' '
    return new


#2

Those two strings are slightly different, compare them. (different length)


#3

You are adding a blank space at the end of each word that you have replaced. Furthermore, you're not appending (concatenating) words that are not replaced. You can define new text as an empty list, and then split text and iterate through it. If i matches the word then replace it as you have already done, and append it to the list. Else append the non-matching word to the list. When the loop is over, join the members of the list with the blank space between them (as you can see in the return statement on the final line of the code). Hope this helped :slight_smile:

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

#4

Thanks this helped a lot


#5

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