Ric*_*dad 2 python list-comprehension list uppercase
通过“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"))
Run Code Online (Sandbox Code Playgroud)
我想我可以在更大的语句中做到这一点,但有没有人知道如何在一行中正确返回它?我猜这将涉及列表理解。
Ric*_*dad 10
re.sub 有效,但它仍然是不正确的答案并且过于复杂 - @C。Leconte 使用简单替换是正确的。
def highlight_word(sentence, word):
return(sentence.replace(word,word.upper()))
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"))
Run Code Online (Sandbox Code Playgroud)
谢谢