我需要编写一个函数,它接受两个字符串(文本和单词)并返回用星号替换所选单词的文本(星号的数量应与审查单词中的字母数量相对应。)。
例如:
如果 text="hey hey hey" 且 word="hey" 返回的文本应该是:
'*** *** ***'
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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))
Run Code Online (Sandbox Code Playgroud)
该代码有效,但返回:
*********
Run Code Online (Sandbox Code Playgroud)
并不是
*** *** ***.
Run Code Online (Sandbox Code Playgroud)
一旦我使用该行:
return ("_".join(text_with_asterisks))
Run Code Online (Sandbox Code Playgroud)
相反我得到:
'***_***_***'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么“”被忽略以及如何在单词之间添加空格。
谢谢!
当您加入星号时,您将获得额外的空间:
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))
Run Code Online (Sandbox Code Playgroud)
censor("hey hey hey", "hey")输出你想要的 ( '*** *** ***')
我只是指出了你的错误,但肯定有一种更优雅、更有效的方法来完成你想要的事情。