0

The function should return the text with the word replaced with asterisks. Not sure why my original code wouldn't work as the logic seems correct to me.

text = "this shit is cool"
def censor(text, word):
    lst = text.split()
    ast = ""
    result = ''
    for char in word:
        ast += "*"
    for wrd in lst:
        if wrd == word:
            wrd = ast    #why doesn't this part work??

    print " ".join(lst)

censor(text, "shit")

This is my corrected code after I looked up some other related problems. It just seems more complex and unnecessary. Why does this one work instead of my original code?

def censor(text, word):
    lst = text.split()
    ast = ""
    result = ''
    for char in word:
        ast += "*"
    for wrd in lst:
        if wrd == word:
            loc = lst.index(word)     #I can't just change it directly? using wrd?
            lst[loc] = ast

    return " ".join(lst)
rookiesix
  • 13
  • 3

1 Answers1

0

Try this:

def censor(text,word):
    return text.replace(word,'*'*(len(word)))
Jorge E. Hernández
  • 2,800
  • 1
  • 26
  • 50