根据列表中的匹配词将单词大写

新手上路,请多包涵

在学习“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"))

我想我可以在一个更大的声明中做到这一点,但有谁知道如何在一行中正确返回它?我猜这将涉及列表理解。

原文由 Richard Modad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 292
1 个回答

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

谢谢

原文由 Richard Modad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题