基于列表中的匹配单词大写单词

问题描述 投票:0回答:1

通过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"))

我想我可以在较大的语句中执行此操作,但是有人知道如何在标志行中正确返回此值吗?我想这将涉及列表理解。

python list list-comprehension uppercase
1个回答
0
投票

一行,以@Barmar提示的方式:

highlight = lambda phrase, word: " ".join([x.upper() if x == word else x for x in phrase.split()])
© www.soinside.com 2019 - 2024. All rights reserved.