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 + " "
        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


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.


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
            new = new + i + " "
    new_i = new.rstrip()  


What does rstrip() function do?

new_i = new.rstrip()


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


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


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


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