Practice makes perfect -> Censor


#1



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


Hello, i have a problem with the following code, when the input is censor('hey hey hey', 'hey') the code just returns 'hey hey hey' (instead of '*** *** ***'), so the problem is probably in the last loop, but I don't see the mistake. Thanks for any replies


def censor(text, word):
    lst = text.split()
    first = word[0] # first char in word
    for item in lst: # looping through lst
        if item == first: # checking if item (character) equals the first letter in word
            for i in range(1, len(word)): # if it does, we loop to check if other chars equal other chars in the word
                if not lst[item + i] == word[i]:
                    break
            else: # if the loop finishes, we replace looped chars with asterisks
                for j in range(len(word)):
                    lst[item + j] = '*'
    result = ''.join(lst) 
    return result


#2

here:

for item in lst: # looping through lst

this will give you each word in the list:

for item in lst: # looping through lst
    print item

which will output:

hey
hey
hey

this should allow you to simplify your solution


#3

Maybe I don't understand .split, what does it do?


#4

feel free to code in the exercise to see what certain code does:

def censor(text, word):
    lst = text.split()
    print lst

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

it splits the string into a list. Given you don't specify a separator for split the default (a space, " ") is used causing the words to be the elements in the list


#5

Thank you! That makes it a lot easier


#6

you can also decide not to use split if you feel adventurous, quit an interesting solution that will be.

If you need more help, post an updated version of your code. But with split, i think you can easily manage :slight_smile:


#7

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