我需要编写一个函数,它接受两个字符串(文本和单词),并返回所选单词替换为星号的文本(星号的数量应该对应于被审查的单词中的字母数)。
例如:
如果text=“嘿嘿”和word=“嘿嘿”,返回的文本应该是:
'*** *** ***'这是我的代码:
def censor(text,word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(' '.join(asterisks))
return (" ".join(text_with_asterisks))代码工作正常,但它返回:
********* 而不是
*** *** ***. 一旦我用了这句话:
return ("_".join(text_with_asterisks))相反,我得到了:
'***_***_***'我不明白为什么“”会被忽略,以及如何在单词之间添加一个空格。
谢谢!
发布于 2015-08-25 09:32:20
当你加入星号时,你有一个额外的空间:
def censor(text, word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(''.join(asterisks)) #here's the culprit
return (" ".join(text_with_asterisks))censor("hey hey hey", "hey")输出您想要的东西('*** *** ***')
我只是指出了你的错误,但肯定有一个更优雅和更有效的方式来做你想做的事。
https://stackoverflow.com/questions/32200262
复制相似问题