Censor


#1




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


I have this error and don't know where I get wrong
Besides,
I 'm wondering about the 'Return'
What is the exact function of Return?
And in this exercise, what should I return
Thanks alot

def censor(text, word):
    text = text.split()
    length = len(word)
    for char in text:
        if char == word:
           char = '*' * length
    
    new = ' '.join(text)
    return new
y = censor("hey hey hey","hey")


#2

your for loop:

for char in text:

char will get assigned each word from text (in order). look:

def censor(text, word):
    text = text.split()
    length = len(word)
    for char in text:
         print char

y = censor("hey hey hey","hey")

but char variable only exist inside the loop, it won't persist anywhere. So you might update char in an attempt to censor, but it gets assigned a new value in the next iteration of your loop, overwriting your censor attempt.

The purpose of return is that it returns the censored string. you store the result of this in y, so if you print y you get the censored string (after you fixed your code)


#3

Sr but i seem to have no idea to fix my code :frowning:

def censor(text, word):
    text = text.split()
    length = len(word)
    new_text = ''
    for char in text:
        if char == word:
            char = '*' * length
            new_text += char
        else:
            new_text += char
    
    new_text = ' '.join(text)
    return new_text
y = censor("hey hey hey","hey")
print y

#4

you are already much closer.

there is a problem here:

new_text = ' '.join(text)

new_text is already a string, so you don't need to use join()


#5

Oh thank you! I've found out the way to life :slight_smile:
I changed my new_text into a list instead of a string and used .append and .join
But there is a mistake. Can you tell me why?


#6

i need to see how you implanted this, can you provide the code?


#7

Yep. Here it is
def censor(text, word):
text = text.split()
length = len(word)
new_text = []
for char in text:
if char == word:
char = '*' * length
new_text.append(char)

    else:
        new_text.append(char)
new_text = ' '.join(text)

return new_text

#8

you join text together? which contains a list of your original string


#9

OMG, Im so stupid. Thank you so much :slight_smile:


#11

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