10. Censor: Improving my censorship



Hi! So I just got done with this exercise and I wanted to improve upon my code so that I could censor a list of words. As of right now I don't even know where to start so I'd like some help with that. Thanks!

def censor(text,word):
    length_text = len(text)
    length_word = len(word)
    censorship = length_word * '*'
    for x in range(length_text):
        if text[x:x + length_word] == word:
            text = text.replace(word, censorship)
    return text


Before embarking on a multi-word list to censor, we should work out the logic of the single word function, above. I believe the instructions tell us to NOT use the replace() built-in, so this practice needs to go back to the drawing board.


I do not see any instruction to not use the .replace method so that bit is fine.


The problem with using the replace method is that exhibits the entire behaviour that your function should implement, it does everything - yes, that also means that if you were to use that method then the code should be a one-liner and everything else is doing a whole lot of nothing.
The spirit of the exercise is to think about what actions need to be carried out to get the desired result, and yes, you are doing some of that, but there's still the issue of what is the rest of the code doing if replace already has the whole thing as part of its behaviour?

If you can censor one string, then censoring many strings is just a matter of applying the censoring on each string.


You're completely right, I was just stating that the instructions do not explicitly state that you are not to use that method. I had just finished this same lesson when I came here to see what others had done, and after your reply I will go back and try to do it again without using .replace because I agree it may not have been in the spirit of putting all the lessons into use.


Of course - what you do with that information is entirely up to you - I just want to make sure you have it, as you can then argue yourself for that the existence of str.replace obsoletes this censor function and so to make sense out of the exercise we in turn need to ignore the existence of str.replace


And nor would have I had one gone back in and looked. Must have confused it with another lesson that suggests not using built-ins. The point is moot, now, as I see.


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