Censor string challenge


#1

Can someone help me figure out what am getting wrong here.

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

#2

why do people always decide to use a loop when using the built in .replace() function? replace can find all instances of the word for you, and replace them with the required asterisks

Either use .replace(), but then you don't need any loops. Or make a empty lists and append the censored word when needed (use if condition) else append the uncensored word, and then join it together


#3

Thank you for the help
I have finally decided to go with the loops and append

still trying to figure out how get the job done using the .replace function


#4

Can you elaborate on how to use the .replace function? I searched online and found this formatting: string.replace(old,new) where s is the string to search through.

def censor(text,word):
    words= word.split()
    words_string= str(words)
    new= words_string.replace(word,"*"*len(word))
    return ''.join(new)

I get this error

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


#5

this bit is good:

.replace(word,"*"*len(word))

but you want to replace the words in text with * times length of word. so you can do:

text.replace(word,"*"*len(word))

that is it, it is just one line. replace is doing everything for you.


#6

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