反轉句子中每個單詞的 Python 程式?


我們這裡使用了python中內建的函式。首先我們將句子分解成一個單詞列表。然後反轉每個單詞並建立一個新列表,這裡我們使用python列表推導技術並最後連結新單詞列表並生成一個新句子。

範例

Input :: PYTHON PROGRAM
Output :: NOHTYP MARGORP

演算法

Step 1 : input a sentence. And store this in a variable s.
Step 2 : Then splitting the sentence into a list of words.
   w=s.split(“”)
Step 3 : Reversing each word and creating a new list of words nw.
Step 4 : Joining the new list of words and make a new sentence ns.

示例程式碼

#  Reverse each word of a Sentence
 # Function to Reverse words
def reverseword(s): 
   
   w = s.split(" ")        # Splitting the Sentence into list of words.
                           # reversing each word and creating a new list of words
                           # apply List Comprehension Technique
   nw = [i[::-1] for i in w]
                           # Join the new list of words to for a new Sentence
   ns = " ".join(nw)
   return ns
# Driver's Code 
s = input("ENTER A SENTENCE PROPERLY ::")
print(reverseword(s))

輸出

ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM
NOHTYP MARGORP

更新於: 30-Jul-2019

3K+ 檢視

職業起步

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.