通过Coursera Python课程学习,我遇到很多麻烦。
Highlight_word函数将句子中的给定单词更改为其大写形式。例如,highlight_word(“ Have a nice day”,“ nice”)返回“ Have a NICE day”。您可以只用一行编写此功能吗?
def highlight_word(sentence, word):
return(___)
print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(highlight_word("Automating with Python is fun", "fun"))
我想我可以在较大的语句中执行此操作,但是有人知道如何在标志行中正确返回此值吗?我想这将涉及列表理解。
一行,以@Barmar提示的方式:
highlight = lambda phrase, word: " ".join([x.upper() if x == word else x for x in phrase.split()])