10. Censor


#1



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


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


I am not sure what to do. For some reason, I can't get the key in the text to be replaced with censor. Please, someone help, because I am getting really frustrated.


def censor(text, word):
    text.split()
    censor = "*" * len(word)
    for key in text:
        if key == word:
            key = censor
    return text
print censor("this hack is wack hack", "hack")


#2

@pickle0323,

You will want to use some print statements
to get an idear what you are doing.

def censor(text, word):
    text = text.split()
    print text
    censor = "*" * len(word)
    print censor
    print "==================="
    for key in text:
        print key
        if key == word:
            #now you re-assign the VARIABLE key 
            #with the Value of the Value of the VARIABLE censor
            #you are NOT replacing the key-Value in the text-Array
            key = censor
    print "===the return ==="
    print text
    return text
print censor("this hack is wack hack", "hack")

You will some-how
either create a =result-Array= filling it with =key=
or replace the Array-Element in the Original =text= Array

For syntax help, use google search
== discussions / opinions ==
python [your question] site:stackoverflow.com
or
== the Book ==
[your question] site:python.org


#3

I used enumerate() to find the index of the word to be censored and replaced it with * as follows.
First I split the word to turn it into a list (and it's actually a good idea to print at each stage to just see if what you are doing is correct) then I iterated through the list using the "for" and "enumerate()" function. now what enumerate does (and forgive my explanation if it's a bit lay) is that it gives you the elements (n) in the list and their indixes(i). If the element is equal to the word you want to censor then you access that element (n) in the list like this list[n] and then you replace it with whatever censoring sign you want to use (* or @). The *len(word) ensures that you insert the number of stars that correspond to the length of the word being censored. After you get all your * you want to join them together using " ".join(list). Ensure that there's a space between the "".

def censor(text, word):
text = text.split()
for n,i in enumerate(text):
if i == word:
text[n] = "*" * len(word)
return " ".join(text)


#4

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