在Python中替换列表元素

2024-04-28 13:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

函数应该返回文本,并用星号替换单词。 我不知道为什么我原来的代码不能工作,因为我觉得逻辑是正确的。你知道吗

text = "this shit is cool"
def censor(text, word):
    lst = text.split()
    ast = ""
    result = ''
    for char in word:
        ast += "*"
    for wrd in lst:
        if wrd == word:
            wrd = ast    #why doesn't this part work??

    print " ".join(lst)

censor(text, "shit")

这是我在查找其他相关问题后更正的代码。只是看起来更复杂,更没必要。为什么这个能代替我原来的代码?你知道吗

def censor(text, word):
    lst = text.split()
    ast = ""
    result = ''
    for char in word:
        ast += "*"
    for wrd in lst:
        if wrd == word:
            loc = lst.index(word)     #I can't just change it directly? using wrd?
            lst[loc] = ast

    return " ".join(lst)

Tags: 代码textinfordefresultthisast