Python 15.Practice Makes Perfect


Hello friends,I am once again seeking your help with this excercize:

I get following error message

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

def censor(text,word):
    string=" "
    for i in split:
        if i==word:
        string=string+" "+i
    return string
print censor ("hey hey hey","hey")
print censor("do unto others","unto")
print censor ("do unto others,what do you do yourself","do")

What's wrong with my code.for what its worth,this is my output

 *** *** ***
  do **** others
  ** unto others,what ** you ** yourself


Compare the two. Your code must be inserting a space character.


Sorry I don't understand.Do you mean I should create extra space between individual words?


I think you mean to say this space "[ ]*** *** ***".Am I right? Can you provide any pointers, to shave it off?


There's the insertion. Now you just need to figure how NOT to do that in the first instance.

This is not a likely solution, but it may work for the time being while a re-think is underway...

string += " " + i if len(string) else i

Corrrection. The real insertion point is the way the string is defined to begin with.

 string=" "

Lesson being that we never define a string with a leading space.

>>> def censor(text,word):

    for i in split:
        if i==word:
        string += " " + i if len(string) else i
    return string

>>> print (censor ("do unto others as you would have others do unto you","do"))
** unto others as you would have others ** unto you

Otherwise known as a literary parallelism where we can put any verb we choose in the placeholder/argument.


This is bothersome. It doesn't really tell the reader anything. We can see that it is a split, but of what?

text = text.split()

Since we never refer to text in your previous code, then why not mutate it, and save creating another variable for the reader to track. Is readability beginning to make more sense by this one change?


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