10. Censor, need more stars


#1
  1. Censor, Practice Makes Perfect

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

Seems to be something wrong with the stars variable, but it looks solid to me.

def censor(text, word):
    censored = ""
    word_list = text.split()
    for item in word_list:
        if item == word:
            stars = "*" * len(word)
            censored = " ".join(stars)
        else:
            censored = " ".join(item)
    return censored

Thanks!


#2

last lines of code is wrong in order to replace the word you need to find the index first in the text in order to do it you can use built in function called enumerate()
def censor(text, word):
censored = ""
word_list = text.split()
for index, item in enumerate(word_list):
if item == word:
star = "*"*len(word)
item = star
word_list[index] = star
return word_list

so what we did here is we found the index of the word in the text and replaced it with stars.
let me know if you get any errors.


#3

I had to output the word_list as a string, but besides that it worked fine. Thanks!

def censor(text, word):
    word_list = text.split()
    for index, item in enumerate(word_list):
        if item == word:
            star = "*" * len(word)
            word_list[index] = star
    return " ".join(word_list)

Very neat, thanks again.

Looks like my original code didn't work because "Join" wasn't joining the existing censored variable with the stars, it was just writing over censored with the stars.

  • John

#4

here is my simple solution, hope it helps

def censor(text,word):
    a = ""
    for i in range(len(word)):
        a += '*'
    text = text.replace(word, a);
    return text

#5

Hello, there was a mistake in your code, this one works.

You forgot to re-use i if you see below.

def censor(text,word):
a = ""
for i in range(len(word)):
a += '*'
i = text.replace(word,a);
return i


#6

Could somebody help me?
When i write this code i get a mistake "Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "" when it should return "*** *** ***".

def censor(text, word):
result = ""
while word not in text:
result = result + text.replace(word, len(word)* "*")
return result

But when i write this code everything is ok

def censor(text, word):
result = ""
while word not in text:
result = result + text.replace(word, len(word)* "*")
return text.replace(word, len(word)* "*")

Why it is so?