1

I'm working through simple exercises in an online Python course - an exercise called "censor" takes 2 inputs, a sentence and word - then returns the sentence with all instances of the given word replaced by asterisks. The number of asterisks in each replacement equals the number of characters in the original word. For simplicity's sake the exercise assumes no input error checking is needed. My code works but I'm wondering if it can be made more efficient?:

def censor(text, word):
    textList = text.split()
    for index, item in enumerate(textList):
        count = 0
        if item == word:
            for char in word:
                count += 1
            strikeout = "*" * count
            textList[index] = strikeout
            result = ' '.join(textList)
    return result
10
  • 5
    "My code works but I'm wondering if it can be made more efficient?" That typically is better suited question for Code Review Commented Oct 12, 2015 at 12:55
  • For a start, note that textList[index] = '*' * len(word) would be neater and probably more efficient than the separate count loop.
    – jonrsharpe
    Commented Oct 12, 2015 at 12:56
  • 2
    Am still pretty new to this forum. Lots of "rules" to absorb it seems :-) Is there a way for me to move it, rather than needing to re-enter?... And... I thought I was just in a general, "post any question" area... how do I identify the sub-forum I'm in?
    – Margarita
    Commented Oct 12, 2015 at 12:57
  • It says that on the top of the screen.
    – pppery
    Commented Oct 12, 2015 at 12:59
  • Actually, I just see "Stack Overflow" which I thought was the overarching title for a 'family' of various category-specific sites (such, as apparently" a "Code Review" site?
    – Margarita
    Commented Oct 12, 2015 at 13:05

1 Answer 1

7

There is already a function on string objects that does this:

def censor(text,word):
    return text.replace(word, "*"*len(word))
2
  • Thanks so much! Glad your answer made it through before I got shut down. If I can find it, I'll check out the Python source for .replace and see how they did it. Go straight to the source, as it were :-)
    – Margarita
    Commented Oct 12, 2015 at 13:00
  • You should accept my answer then. Also, the python source for built in functions is written in C.
    – pppery
    Commented Oct 12, 2015 at 13:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.