在Python中,如果你想要倒置一个句子中的单词顺序,但保持单词内部的字母顺序不变,你可以使用 `split` 和 `join` 方法。下面是一个简单的函数,可以实现这个功能:
def reverse_words_in_sentence(sentence):
使用split方法将句子分割成单词列表
words = sentence.split()
使用reverse方法将单词列表倒置
words.reverse()
使用join方法将倒置后的单词列表重新组合成句子
reversed_sentence = ' '.join(words)
return reversed_sentence
使用这个函数,你可以将一个句子中的单词顺序倒置,例如:
original_sentence = "I like beijing."
reversed_sentence = reverse_words_in_sentence(original_sentence)
print(reversed_sentence) 输出: beijing. like I
这个函数会将句子中的单词顺序倒置,但保持单词内部的字母顺序不变,并且会去除句子首尾的空格。如果你需要保留首尾的空格或者有其他特殊要求,你可能需要对这个函数进行相应的调整