Skip to main content
 首页 » 编程设计

python之反转句子中的一个词

2025年05月04日19yjmyzz

我正在尝试创建一个从句子中反转单词的函数。我的部分代码工作正常 但我无法完成我想要的。下面是我创建的功能。我只想要“语言” 撤销。输出应该像“Python is an interesting egaugnal to learn”。我怎样才能完成 这个

    def reverse(sentence,reverse_word): 
        i = sentence.find(reverse_word) 
        reverse_sentence = sentence[:i] + reverse_word[::-1]  
            return reverse_sentence 
   reverse("Python is an interesting language to learn","language") 

以上代码对代码进行反转,最多返回反转后的单词。我无法完成 反向单词后的单词。感谢您的帮助。

请您参考如下方法:

一个解决方案是用它的反向版本替换这个词

text = "Python is an interesting language to learn" 
word = "language" 
text.replace(word, word[::-1]) 

输出

Python is an interesting egaugnal to learn

即使单词出现多次也有效。


但是请注意,在上述解决方案中,languages 将变为 egaugnals。

如果您只想在整个单词匹配时反转,请使用:

import re 
re.sub(r'\b'+word+r'\b', word[::-1], text) 

在这个解决方案中,

Python is an interesting language to learn like many other languages

会变成

Python is an interesting egaugnal to learn like many other languages