Censor not working!


#1

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

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

def censor (t,w):
    l=len (w)
    c="*"*l
    li=t.split()
    for i in li:
        if i==w:
            i=c
    t=" ".join(li)  
    return t

#2

Changing i will have no effect on li.

One way around this is with the list.index() method.

j = li.index(i)

Now we can access that index in the main object.

li[j] = c

This is not a complete solution, though. Try it...

def censor (t,w):
    l=len (w)
    c="*"*l
    li=t.split()
    for i in li:
        if i==w:
            li[li.index(i)] = c
    t=" ".join(li)  
    return t

>>> censor("hey, hey, hey", "hey")
'hey, hey, ***'

It's not what the SCT is checking for. That will pass. But it raises the issue of special characters. str.split() preserves punctuation. We can see above that there are two, hey,'s. The commas are string characters, not delimiters so are printable.

Notwithstanding that you can pass this lesson with a slight edit, how might we address the special character issue? Something to think on when time allows.

This came up in an earlier topic that you might find interesting.

https://discuss.codecademy.com/t/censoring-is-an-endless-job/78987/7

Applying what we learned there, gives,

def alpha(x):
    return ''.join(filter(lambda a: a.isalpha(), x))
def censor(t, w):
    c = "*" * len(w)
    li = t.split()
    for i in li:
        if alpha(i) == w:
            li[li.index(i)] = c
    t = " ".join(li)  
    return t

>>> censor("hey, hey, hey", "hey")
'*** *** ***'

#3

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