Codeacademy的python censor函数

时间:2016-01-05 18:26:25

标签: python

def censor(text, word):
    final_text = ''
    new_text = ''
    items = text.split()
    for i in items:
        if i == word:
            new_text = "*" * len(word)
            final_text.join(new_text)
        else:
            new_text = items
            final_text.join(new_text)
    return final_text

print censor("this hack is wack hack", "hack")

上述功能旨在审查单词" hack"文字中有星号。我可以知道上面代码中的缺陷在哪里。先感谢您。

1 个答案:

答案 0 :(得分:1)

这应该是它。

def censor(text, word):
    final_text = ''
    new_text = ''
    items = text.split()
    for index, w in enumerate(items):  #'index' is an index of an array
        if w == word:
            new_text = "*" * len(word)
            items[index] = new_text # substituting the '*'
    final_text = ' '.join(items)    # the correct way how join works
    return final_text

print censor("this hack is wack hack", "hack")

另一种方式:

text = 'this hack is wack hack'
word = 'hack'
print text.replace(word, '*' * len(word)) 

join()在python中的工作方式是你在连接符号上执行它(例如'',' - ',','等),然后在连接中提供列表( list_in_here)

简单示例:

>>>'-'.join(['1','human','is','a','one'])
'1-human-is-a-one'