Skip to main content
 首页 » 编程设计

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

2025年05月04日14freeliver54

我正在完成一个在线 Python 类(class)中的简单练习 - 一个名为“审查员”的练习需要 2 个输入,一个句子和一个单词 - 然后返回句子,其中给定单词的所有实例都被星号替换。每个替换中的星号数等于原始单词中的字符数。为简单起见,练习假设不需要输入错误检查。我的代码有效,但我想知道是否可以提高它的效率?:

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))