Result is correct but I still get an error message


#1

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

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

Question:
My function returns the same result as it should return. Why does it result in a error message?

My code:

def censor(text,word):
    new_string = ""
    for char in text:
        if char in word:
            new_string += "*"
        else:
            if char == " ":
                new_string += " "
            new_string += char
    return new_string

#2

Compare yourself.

result = censor('hey hey hey', 'hey')
expected_result = '*** *** ***'
print result == expected_result
print repr(result)
print repr(expected_result)

False
`***  ***  ***`
`*** *** ***`


#3

```
def censor(text,word):
    for x in word :
        text = text.replace(word,'*'*len(word))
    return text
print censor("this hack is wack hack", "hack")

`
This is another easy way :wink:


#4

the replace function does everything that censor is meant to do, you might take that as a hint that you're meant to implement that functionality yourself, not use a function that already has it!

Also, since replace already does what censor should do, there is no need to use a loop, replace does everything all in one go (censoring text is to replace one string with asterisks)


#5

But as far as i can remember in the exercise there was nothing that tells us not to use it :confused:


#6

Thanks for the tip! I figured I should go with the built in replace function, just wanted to make it harder for myself and try to do a function. I was only a bit purplexed when my functions result was similar to the result it should have given.


#7

Thats a neat tip. Thanks for the helpful answers!


#8

Using replace is just avoiding the exercise. Better to practice with basic operations to develop problem solving, a skill to later be applied to more complicated scenarios where you'll need to be very methodical to sort out problems.


#9

Nice, I appreciate your response :slight_smile:


#10

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