我试图找出为什么我的代码的一个版本有效,而另一个版本没有。
赋值的目的是创建一个名为censor
的函数,它将两个字符串(文本和单词)作为输入。它应该返回带有您选择用星号替换的单词的文本。
这是我编写的第一段代码,但它没有用。
def censor(text, word):
import string
text = string.split(text)
for index in range(0, len(text)):
if word == text[index]:
text[index] = len(word) * '*'
text = string.join(text)
return text
上面的代码段返回了一个错误:
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "* * * h e y h e y" when it should return "*** *** ***".
第二段代码如下,并且确实有效。
def censor(text, word):
import string
text = string.split(text)
for index in range(0, len(text)):
if text[index] == word:
text[index] = "*" * len(word)
return " ".join(text)
我不明白为什么text = string.join(text)
在" ".join(text)
期间无法正常工作。
答案 0 :(得分:0)
阅读string.join
。您应该在要加入join
的字符串上调用text
。例如,
>>> ', '.join(['a', 'b', 'c']
'a, b, c'
答案 1 :(得分:-1)
您可以使用正则表达式更轻松地完成此操作:
import re
def censor(text, word):
return re.sub(r'\b' + word + r'\b', '*', text)