Censor


#1



Help me solve this problem, i don't know how to fix it.
Thanks for every reply

Oops, try again. Your function fails on censor("Yo go fro yo go","go"). It returns "** **" when it should return "Yo ** fro yo **".


def censor(text,word):
    txt = text.split()
    tt = []
    for i in txt:
        if i == word:
            i = len(word) * '*'
            tt.append(i) 
    return " ".join(tt)


#2

With respect to your code, You're just putting censored word (in form of *'s) in your list, but you also need to put words that are not censored word.

cus when we return It will have only *'s (censored word)
Introduce an else - block and append the non-censored words too.

Also you can put this line outside of loop, as its a constant string as it does not changes ,In your code It keeps assigned at every loop.

i = len(word) * '*'

save it at starting of your function say..

c = len(word) * '*' and append c to list.


#3

Thank you ,greentreemee
I took your advise, fix my problem.
My code can work now.

thank you again!

def censor(text,word):
    txt = text.split()
    tt = []
    for i in txt:
        if i == word:
            i = len(word) * '*'
            tt.append(i) 
        else:    
            tt.append(i) 
    return " ".join(tt)

#4

came up with this ...try it out its compact and does the job better than splitting your string into a list as that method may not censor in all situations

def censor(text,word):
x = text.replace(word, " * " * len(word))
return x

e.g. if the censor word is "code" and if its used in its verb form or is concatenated to any other character like in the word "coding"
or "coded" the split method wont censor it afaik, but the code above will censor the given key word even if its appended or is a part of other words like ----> coding = ****ing which i think is a better method for censoring overall


#5

For the lessons its better to write your own algorithm, rather then using a built in function like .replace() which does all the work for you, after all, you are here to learn

That ultimately depends on what the code needs to do, there is no best in programming, it depends on the goal

for example this forum has a foul language fillter, hell gets censored (unless like me use markup) but you don't want hello to become ****o, hello is not a foul word.


#6

yeah that was the reason i did the the long way the first time too


#7

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