Censor


#1



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


My function fails on censor("hey hey hey","hey"). It returns "* * *" when it should return "*** *** ***".


I think the "string" in "text" is replaced. But I don't know why my "*"doesn't duplicate the length of "string".


def censor(text,string):
    r=""
    ss=text.split()
    for n in ss:
        if n==string:
            n = "*" * len(string)
        else:
            n=n
        r=" ".join(n)
    return r


#2

Should this be an empty list? r = []

Would this be appended to the list?

r.append( ... )

#4

Thanks! It works. It seems that I used join() in wrong way.


#5

Recall that join combines string values to form a single string when applied to a list. It also inserts characters when applied to a string...

":)".join("Happy Coding! ".split())

#6

Thanks guys for the answers.
I was finally able to write the code properly.

r=" ".join(n)

as r is an empty list i.e r= [], instead of join use append here:

r.append(n)

now we have r = [***, ***, ***] and to get rid of brackets and commas, use join with a space " "

re = " ".join(r)

so now we have re = *** *** *** when we use return re:


def censor(text,string):
    r=[]
    ss=text.split()
    for n in ss:
        if n==string:
            n = "*" * len(string)
        else:
            n=n
        r.append(n)
        re = " ".join(r)
    return re
    
print censor("hey hey hey", "hey")

#7

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