10. Censor - extra *


#1



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


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


I'm expecting a "*** *** ***" But i'm not sure where the extra * from the middle part come from
Any help?


censored = []
empty = " "

def censor(text, word):
    x = text.split()
    t = ""
    new_word = ""
    for each in x:
        if each == word:
            new_word = each.replace(each, "*" * len(each))
            censored.append(new_word)
            t = empty.join(censored)
            return t 
    
censor("hey hey hey", "hey")


#2

Im not sure but I think you should replace len(each) with len(word)


#3

tested it, but it gives the same error "*** **** ***"


#4

I don't see what is going on to cause that error. I do think you could minimalize this code a bit though. There are a couple steps that seem redundant. Here is mine for reference.

def censor(text, word):
    new_sen = []
    old_sen = text.split()
    for each in old_sen:
        if each == word:
            new = "*" * len(each)
            new_sen.append(new)
        else:
            new_sen.append(each)
    return " ".join(new_sen)

#5

What about the simple:

def censor(text, word):
word_ast = "*" * len(word)
text = text.replace(word, word_ast)
return text
print censor("Hello world, Goodbye world", "world")

Seems to work for me.


#6

I did same way :smiley:

def censor(text, word):
return text.replace(word, "*" * len(word))


#7

Or not we could even not use replace but use the fact that text.split() splits the test into a list

def censor(text, word):
splitted = text.split(" ")
for index in range(len(splitted)):
if splitted[index] == word:
splitted[index] = "*" * len(word)
return " ".join(splitted)


#8

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