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

2024-10-01 17:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在学习“CourseraPython”课程时,我遇到了很多麻烦

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

我想我可以在一个更大的语句中这样做,但是有人知道如何在一行中正确地返回它吗?我猜这将涉及一个列表理解


Tags: 函数版本have单词句子课程wordnice
3条回答

可以用regular expression using re.sub完成

def highlight_word(sentence, word):
  return re.sub(r'\b' + word + r'\b', word.upper(), sentence)

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

谢谢

以@Barmar暗示的方式在一行中给出部分答案:

def highlight_word(sentence, word): return " ".join([x.upper() if x.lower() == word.lower() else x for x in sentence.split()])

基本上-将句子拆分为单词,并使用列表理解来匹配单词。然后使用join()将句子重新组合在一起

编辑:句子.split()将只在空白处拆分,因此它不会将第二个示例大写为“loud!”=“大声”。在本例中,您可以使用regex library进行替换

是的,它可以工作: enter image description here

相关问题 更多 >

    热门问题