10.censor


#1



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):
    change=""
    change="*"*len(word)
    g=text.split()
    for words in text:
        if word==words:
            g[words]=change
    return text


#2

Simplifying things up, you could do:

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

Output:

We are ***

#3

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


#4

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:


#5

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

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


#6

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)


#7

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