Censor: Did I cheat?



So I remember seeing string.replace( ) somewhere before I started this exercise. I added it and played around with it, and after working through a few error messages I was a bit surprised when it worked. Makes me feel like I'm playing the system. Is this a cheap way to solve it in regards to what codecademy wants?

def censor(text, word):
    for h in text:
        j = len(word) * "*"
        return text.replace(word, j)


It depends on what you have learned, so far. How well do you understand the algorithmic approach to solving this problem? There is no harm in finding a 'better' way if you have something to improve upon (meaning you've done the heavy lifting already).

We don't need this line. string.replace() is greedy by default (if we don't include a count parameter) so will replace all occurances of 'word'.

For your example, everything can be written into a one line return statement.

    return text.replace(word, len(word) * "*")

We can even simplify this further and write it as a lambda expression:

censor = lambda text, word: text.replace(word, len(word) * "*")


Thanks for the reply. I'm now somewhat convinced that I should go back and take one of the longer, heavier routes. I feel that it would have been much more challenging had I not used replace.