python - 搜索和替换句子中给定单词的最有效代码?

python - most efficient code to search for, and replace, given word in a sentence?

我正在完成一个在线 Python 课程中的简单练习 - 一个名为 "censor" 的练习需要 2 个输入,一个句子和一个单词 - 然后 returns 带有所有实例的句子给定单词的替换为星号。每个替换中的星号数等于原始单词中的字符数。为简单起见,练习假设不需要输入错误检查。我的代码有效,但我想知道是否可以提高它的效率?:

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

字符串对象上已经有一个函数可以执行此操作:

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