Censor with .replace function


#1



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


Hi All,

My code results in the error below:

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


How can I get rid of the extra " " at the end of line.

Thanks


def censor(text,word):
    for y in text.split():
        if y == word:
           a = y.replace(y,'*') * len(y) + " " 
           a = "".join(a) * (len(y))
    return a


#2

using replace allows for a single line solution, i am not sure what you are doing, can you explain your logic so i can correct the problem?

well, you can always use string slicing to get rid of the additional space at the end, but ideally you would fine tune your solution (preferable without replace)


#3

Hi Stetim94,

Thanks for your reply.
I am trying to replace any occurrence of "word" in text.split with an "*" equal to the length of word.
I have found other non .replace solutions :slight_smile:
Can you kindly show me how to slice off the last space (" ") at the end.

Thanks.


#4

this exactly what replace() is suppose to do? it finds all occurrences in string and replaces them, nothing left for you to do any more

well, you used string slicing in pyg latin:

print "hello world"[0:6]

#5

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