📌  相关文章
📜  Python|反转句子中的每个单词

📅  最后修改于: 2022-05-13 01:54:25.892000             🧑  作者: Mango

Python|反转句子中的每个单词

给定一个长句子,在句子本身中单独反转句子的每个单词。
例子:

Input : Geeks For Geeks is good to learn
Output : skeeG roF skeeG si doog ot nrael

Input : Split Reverse Join
Output : tilpS esreveR nioJ

我们将使用 Python 的内置库函数来单独反转字符串本身中的每个单词。

先决条件:
1.拆分()
2. Python中的逆向技术
Python中的列表理解方法
4. 加入()

  • 首先将句子拆分为单词列表。
  • 分别反转列表中字符串的每个单词。
  • 将列表中的单词连接起来组成一个新句子。

下面是上述想法的实现。

# Python code to Reverse each word
# of a Sentence individually
  
# Function to Reverse words
def reverseWordSentence(Sentence):
  
    # Splitting the Sentence into list of words.
    words = Sentence.split(" ")
      
    # Reversing each word and creating
    # a new list of words
    # List Comprehension Technique
    newWords = [word[::-1] for word in words]
      
    # Joining the new list of words
    # to for a new Sentence
    newSentence = " ".join(newWords)
  
    return newSentence
  
# Driver's Code 
Sentence = "GeeksforGeeks is good to learn"
# Calling the reverseWordSentence 
# Function to get the newSentence
print(reverseWordSentence(Sentence))

输出:

skeeGrofskeeG si doog ot nrael

Python以其短代码而闻名。我们将使用更少的代码行完成相同的任务。

# Python code to Reverse each word
# of a Sentence individually
  
# Function to Reverse words
def reverseWordSentence(Sentence):
  
    # All in One line
    return ' '.join(word[::-1] for word in Sentence.split(" "))
  
# Driver's Code 
Sentence = "Geeks for Geeks"
print(reverseWordSentence(Sentence))    

输出:

skeeG rof skeeG