我想创建一个函数,该函数将高亮显示给定单词的每一次出现
我理解它为什么会这样,但我不知道还有什么其他方法可以让它工作得更近,所以你的帮助真的会帮助我!😊 我试着将不同的最终结果保存到一个列表中,但我该如何将它们连接到最后一句话中呢
def highlight_words(sentence, words):
final = ""
k = 0
for j in range(len(words)):
for i in range(len(sentence)):
if k != 0:
k -= 1
continue
changed = ""
if sentence.lower().startswith(words[j].lower(), i):
changed = sentence[i:i+len(words[j])].upper()
final += changed
k = len(words[j]) - 1
else:
final += sentence[i]
return final
print(highlight_words("Have a nIcE day, you Nice person!!", ["nice"]))
print(highlight_words("Shhh, don't be so loud!", ["loud", "Be"]))
print(highlight_words("Automating with Python is fun", ["fun", "auTomaTiNG"]))
这是程序打印的内容:
Have a NICE day, you NICE person!!
Shhh, don't be so LOUD!Shhh, don't BE so loud!
Automating with Python is FUNAUTOMATING with Python is fun
如果您在解决方案中不使用任何导入的库,我将不胜感激!提前谢谢
使用递归:-
我认为如果你把外环变成字符串而不是单词,那就容易多了。下面是一个选项
您可以简单地使用
split
和join
这样做:希望有帮助:)
相关问题 更多 >
编程相关推荐