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
textList[index] = '*' * len(word)
would be neater and probably more efficient than the separatecount
loop.