10. Censor. What am I doing wrong here? Plz Help


#1



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


This code looks right to me, but I keep getting the error message: Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***".


def censor(text, word):
    num = int(len(word))
    text.split()
    for item in text:
        if item == word:
            item = "*" * num
        else:
            item = word
    "".join(text)
    return text


#2

item is a variable which gets assigned words from your list (in order), which means in each run of the loop the value is changed, but never stored anywhere, and after the loop item ceases to exist

you can see this:

for item in text:
    print item
print item // will give you an error

see how item gets re-assigned every run? It doesn't get stored anywhere.

You could use range() which gives you indexes which you can use to actually manipulate the list.


#3

Thank you for your reply! Do you think that if I create a new list and append the asterisks to the list (see code below), the code would work?

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

#4

yep, it could work if you store the result of the split somewhere:

text = text.split()

otherwise the result of the split isn't stored anywhere, and if it is a string it going to loop over the letters (rather then the words)

same for join, i would store the result of the join action somewhere (or make it one line by combining the join with the return keyword), when joining together i would separate the words with a space.


#5

I finally did it... This problem was bothering me for several hours. Thank you for helping me! I didn't know that I had to store the split in a variable, but doing that fixed my code.


#6

here is a tip, you could (at the end of your code) add a function call:

print censor("hey hey hey","hey")

this way, you can add print statements inside your function, so you can actually see what is happening, this could also have alerted you to that split wasn't working:

def censor(text, word):
    num = int(len(word))
    text.split()
    print text
    new = []
    for item in text:
        if item == word:
            new.append("*" * num)
        else:
            new.append(item)
    "".join(new)
    return new
print censor("hey hey hey","hey")

You could add more, to see where you go wrong


#7

Hmm, okay. I'll make sure to do this from now on.


#10

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