gpt4 book ai didi

Python,join()函数,在单词之间添加空格

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:49 24 4
gpt4 key购买 nike

我需要编写一个函数,它接受两个字符串(文本和单词)并返回用星号替换所选单词的文本(星号的数量应对应于删减单词中的字母数量。)。

例如:

如果 text="hey hey hey"和 word="hey"返回的文本应该是:

'*** *** ***'

这是我的代码:

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))

相反,我得到:

'***_***_***'

我不明白为什么 ""被忽略,我怎样才能在单词之间添加一个空格。

谢谢!

最佳答案

当你加入星号时你有一个额外的空间:

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") 输出你想要的('*** *** ***')

我只是指出了你的错误,但肯定有一种更优雅、更有效的方法来做你想做的事。

关于Python,join()函数,在单词之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32200262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com