2016-06-07 121 views
0

该函数应返回文本替换为星号。 不知道为什么我的原始代码不会工作,因为逻辑似乎对我来说是正确的。替换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) 

回答

0

试试这个:

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