I need help, maybe I got the fundamentals wrong.

"Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks."

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

this is my code

def censor(text,word):
    for words in text:
        if word==words:
    return text


Simplifying things up, you could do:

def censor(text,word):
    text=text.replace(word,'*' * len(word))
    return text
print censor("We are yes", "yes")


We are ***


Thank you for the elegant solution.
Could you please explain what's wrong in my code?


If you print a scenario of your censor function to your console, you will see that the function does "nothing" really. For instance,

print ("We are here", "here")

will output:

('We are here', 'here')

Closing your eyes to my suggested code, you could split the text as you tried doing and append the word as asterisk and then join. :slight_smile:


def censor(text,word):
length = len(word)
text2 = []
for i in range(0,length):
print text.replace(word,''.join(text2))
return text.replace(word,''.join(text2))

censor("this hack is wack","hack")


Also we can do it with input:

def censor(word, text):
g = word.split()
change = "*" * len(text)
c = 0
for a in g:
if g[c] == text:
g[c] = change
c += 1
b = " ".join(g)
return b

first = raw_input("First Word: ")
second = raw_input("Second word: ")
print censor (first, second)


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