Result is correct but I still get an error message



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

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 += "*"
            if char == " ":
                new_string += " "
            new_string += char
    return new_string


Compare yourself.

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

`***  ***  ***`
`*** *** ***`


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:


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)


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


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.


Thats a neat tip. Thanks for the helpful answers!


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.


Nice, I appreciate your response :slight_smile:


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