Python 15.Practice Makes Perfect


#1

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


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096#


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=" "
    split=text.split()
    
    for i in split:
        if i==word:
            i="*"*len(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
None

#2

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


#3

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


#4

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


#5

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):
    string=""
    split=text.split()

    for i in split:
        if i==word:
            i="*"*len(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.


#6

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?


#7

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