Censor


#1

def censor(text,word):
    spl = text.split()
    lst = " "
    for txt in spl:
        if txt == word:
            txt = len(word) *"*" + ' '
            lst = lst + txt
        else:
            lst = lst + txt
            
    return lst

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


#2

Is this logic right?


#3

here:

lst = lst + spl

spl is a list, list + string is error. You should use txt here to add the word if it doesn't need censoring

here:

        if txt == word:
            txt = "*"
            lst = lst + txt

only one asterisks? what if the word we want to censor has a length of 3,4, 5 or even more? you will need to add as many asterisks as the word is long

Your approach will remove the spaces between the words, you will need to add them.


#4

i will be crazy !:triumph:


#5

i add the spaces ,but it error too.


#6

lets replace the spaces with underscores, it should return:

"***_***_***"

you return:

"_***_***_***_"

getting rid of the space at the start of sentence is easy, because it comes from here:

lst = " "

to get rid of the space at the end of sentence is a bit more tricky, maybe you can use string slicing to remove it?

@xhwang, not when i looked at the code, you edited it after i read it


#7

def censor(text,word):
    spl = text.split()
    lst = ''
    for txt in spl:
        if txt == word:
            txt = len(txt) * '*' + " "
            lst = lst + txt
        else:
            lst = lst + txt
            
    return lst

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


#8


#10

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