Censor


#1

def censor(text, word):
ltext = text.lower()
lword = word.lower()

sltext = ltext.split()
new = ""

for i in sltext:
    if i == lword:
        i = "*" * len(lword)
        new = new +  i + " "
    else:
        new = new +  i + " "
return "".join(new)

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

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

I don't get it


#2

No idea why you lowercased all things, also why we need join when our final returning object is a string?

This brings up problems.
As Youre lowering the original string,You need to make it in original form again with censored words while returning.
Also no need of join() method here.

Things to do..

Get rid of all those code lines that lowers word and text.
Get rid of join().

Finally we will have an extra space in final o/p string, we can get rid of it using string slice.


#3

The error is with the trailing " " after your last ***

.rstrip() will remove your trailing white space.

def censor(text, word):
    text = text.split()
    new = ""
    for i in text:
        if i == word:
            i = len(word) * "*" + " "
            new = new + i
        else:
            new = new + i + " "
    new_i = new.rstrip()  
    return"".join(new_i)

#4

What does rstrip() function do?

new_i = new.rstrip()


#5

rstrip() returns a copy of the string with trailing characters removed.


#6

You meaning trailing white spaces only or can that be any character that I pass in it as an argument?


#7

You can strip off any character, for example:

def trail_snipper(text):
    return text.rstrip("l")

print trail_snipper("pitbull")

This code snips off trailing "l"s and returns "pitbu"

rstrip arg must be None, str or unicode


#8

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