Censor code


#1



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


censor("hey hey hey","hey") works fine, but I get the following on the froyo one:

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

I have reviewed the code, and am trying to figure out why instead of using the original word from the phrase, it is replacing the original word with the word in the variable word.


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

#2

I believe the problem is coming from your else statement. You have told the function to append the input word, rather than the string associated with i. That's why hey hey hey works, because the parameter word matches all the other words in the text string. However, in "yo go fro yo go", you replaced all the "go"s with ** and all the other words with go.


#3

Thank you. That was it. (facepalm)


#4

No worries. I'm only just learning, and troubleshooting really helps me to learn stuff better (as if I don't have enough of my own problems to debug!)


#5

It is the best way to learn, really. Google, and helping others. I should spend more time in the forums, but between learning this, starting a new job, and taking care of my clients (oh, and being mom) time is a commodity I don't have a lot of, so I SUPER appreciate your time. Thanks again.


#6

Time is a crazy luxury when trying to learn to code.

I also saw the same mistake and was going to mention it.

I BREAK MY HEAD with my own exercises but I should spend more time on the forums as well and review the code of others.... This is how I solved it by the way, not convinced it's the best way but I am seeing similarities with everyone. I know that mine is not the best though, because it's filled with bandaids...

def censor(text,word):
    length = len(word)
    newlist = text.split()
    phrase = ""
    for term in newlist:
        if term == word:
            term = "*" * length
            phrase += term + " "
        else:
            phrase += term + " "
    return phrase[:-1]

#7

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