10. censor - Is it working, or not?


#1




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


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

It seems like, this quite simple code is fully functional, but for some reasons, it won´t let me through. I even tested it with a comma, uppercase, numbers - with the result as I expedted. What did I misunderstood?

def censor(text,word):
    word = word.lower()
    num = len(word)
    new = []
    text = text.split(" ")
    for x in text:
        if x == word:
            new += "*" * num + " "
        else:
            new += x + " "
    return "".join(new)

print censor("Hello, how are you?","How")
print censor("hey hey hey","hey")
print censor("123 456 789","456")
print censor("this hack is wack hack", "hack")



#2

The issue that the error is referring to is the space at the end of your returned string. The strip() function can be used to trim the trailing whitespace.


#3

Thanks!

def censor(text,word):
    word = word.lower()
    new = [""]
    text = text.split(" ")
    for x in text:
        if x == word:
            new += "*" * len(word) + " "
        else:
            new += x + " "
    return "".join(new).strip()

works great! :slight_smile:


#4

I had another thought, joining on " " (space) instead of "" should yield the same results.


#5

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