Censor


#1



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


I get the following message when I execute my code "Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***"."


I am struggling to understand why my code is not working


def censor(text, word):
    t = list(text)
    c = ""
    for item in t:
        if item == word:
            for letter in item:
                letter == "*"
    
    c = "".join(t)
    
    return c


#2

when using a for loop, the values you get from the list are read only. Change made to iterator won't persist.

there are two approaches to solve this problem:

  1. create a new empty list or string (you pick which is best), check if word requires censoring, if so, censor and append to list/string. If not, just append the word to the list/string

  2. convert string to list (which you did), loop over the list, figure out a way to get indexes so you can words which requires censoring in the list


#3

I rewrote it to implement the first option but I still get the same error.

def censor(text, word):
    t = list(text)
    temp = []
    c = ""
    
    for item in t:
        if item == word:
            item == "*"
            temp.append(item) 
        else: 
            temp.append(item)
         
    c = "".join(temp)
    
    return c

#4

before your loop, make a variable, multiply the length of word with astrisks, so you get the right number of asterisks.

You need to use split(), otherwise you will just loop over letters. How can a single letter equal a word?


#5

take the given hint! --- use the string.split() and use the len(string) to find the length/no of alphabets in word and put that many asteriks ( "*" * n )... try to do it but if still confused after many trys and if u want to take a look at my answer look bellow:
a
n
s
w
e
r
-
i
s
-
g
i
v
e
n
-
b
e
l
o
w
/
/
/
/
/

//
/
//
//

/
/
/
//

/
/

def censor(text, word):
n= len(word)
for i in word.split():
return text.replace(i, "*" *n)


#6

When you use list(text), the text gets dissected individual letters:
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't']

As a result, you would need to compare the individual letters of word and see if they match that of text and eventually combine both to see whether they are equivalent... which is a tedious process.

So yes, use split() instead: t = text.split(). The result will be a fragmented set of words instead of individual letters:
['this', 'is', 'a', 'test']

One more thing you did not fix from previously, under the if-else statement.

This is a comparison, to see if item is equals to the asterisk.


#9