10/15 censor


In every topic here I see long batches of code to solve the problem. I did it in 4 lines, it seems to work fine and Codecademy accepts it. I can't shake the feeling I messed something up though, since I got such a tiny function.

Here's what I did:

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



What happens if you replace something that isn't there? Don't need to check if it's there first, do you.

How many times is your variable used? You could just immediately return the result.

The exercise probably wants you to get your hands a little dirtier though, can you do it without using str.replace?


Ah I see what you mean by your first two points, didn't think of that.

I'm going to try doing it without str.replace. You're probably right, even though the instructions don't mention it that's probably the point of the excercise.
I'm not even sure if I'm 'supposed' to have knowledge of str.replace at this point in the course, since I picked up little tidbits from other sites and resources as well.

Thank you!


Alright, I redid the excercise, without str.replace this time!

def censor(text, word):
    result = []
    splittext = text.split()
    for wrd in splittext:
        if wrd == word:
            result.append("*" * len(word))
    result = " ".join(result)
    return result

It took a bit of help from the forum, but I got it figured out. It works, and I feel better about the whole thing now (less like I cheated).


You're not and they don't.

And you can't really avoid "powerful" functions because nothing is ever just the basic building blocks in Python. There's a lot going on underneath to make Python the nice language it is.

In general though, it's usually a good idea to rely on built-in functions and libraries, especially for computationally heavy tasks. (Python is not very fast, but libraries written in C can be used to do the heavy lifting)