Censor


#1


Hi, what's wrong with my code?
It gives me this error:
Oops, try again. Your function crashed on ('hey hey hey', 'hey') as input because your function throws a "local variable 'new_result' referenced before assignment" error.

def censor(text, word):
    new = []
    for i in text.split():
        if i == word:
            i = '*' * len(word)
            new.append(i)
        elif i != word:
            new.append(i)
            new_result = ' '.join(new)
    return new_result

print censor("live love life", "life")

#2

I haven't solved it yet, but I think .append() is only for lists not strings


#3

Hi alex_py
Thank you for posting your code. I was trying to do this task and felt I have the idea but missing how to organise them in a code. So, I have changed your code a bit and it worked very well. please look at the code below:

def censor(text,word):
    new = []
    for i in text.split():
        if i == word:
            i = '*' * len(word)
            new.append(i)
        elif i != word:
            new.append(i)
    return ' '.join(new)

print censor('hey hey hello','hello')

#4

Hi, tnx alot, it works now, but why is there any defference between
new_result = ' '.join(new)
return new_result

and

return ' '.join(new)

They do the same thing right?


#5

Hi, you are welcome, we are here to help each other :slight_smile:
I am afraid I don't know we need experts explanation :grin:


#6

hello @arwaahmed
Could you explain the text.split() part? Can't get it


#7

Hi shibaprasad,
Sorry for late reply, here is what I've got from the internet to see what did it mean and I added it as comment in codecdemy editing console like this. Please feel free to copy it and if you have any question please ask.!

def censor(text,word):
    new = []
    for i in text.split():#this part is new for me. It actually separate each word in text. The split function splits a single string into a string array using the separator defined .split(separator).If no separator is defined, *whitespace* is used.
        if i == word:
            i = '*' * len(word)
            new.append(i)
        elif i != word:
            new.append(i)
    return ' '.join(new)

print censor('this hack is wack hack','hack')

I hope this helps :slight_smile:


#8

@arwaahmed Thanks sir! Yes, no doubts now.


#9

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