用 Python 在一個給定的字串中倒序單詞


我們獲得了一條字串,我們的目標是在字串中倒序所有單詞。我們可以使用 split 方法和 reversed 函式來實現輸出。我們來看一些示例測試用例。

Input:
string = "I am a python programmer"
Output:
programmer python a am I


Input:
string = "tutorialspoint is a educational website"
Output:
website educational a is tutorialspoint

讓我們遵循以下步驟來實現我們的目標。

演算法

1. Initialize the string.
2. Split the string on space and store the resultant list in a variable called words.
3. Reverse the list words using reversed function.
4. Convert the result to list.
5. Join the words using the join function and print it.

檢視上述演算法的程式碼。

示例

 線上演示

## initializing the string
string = "I am a python programmer"
## splitting the string on space
words = string.split()
## reversing the words using reversed() function
words = list(reversed(words))
## joining the words and printing
print(" ".join(words))

輸出

如果你執行以上程式,你會得到以下輸出。

programmer python a am I

讓我們再次對不同的輸入執行該程式碼。

示例

 線上演示

## initializing the string
string = "tutorialspoint is a educational website"
## splitting the string on space
words = string.split()
## reversing the words using reversed() function
words = list(reversed(words))
## joining the words and printing
print(" ".join(words))

輸出

如果你執行以上程式,你會得到以下輸出。

website educational a is tutorialspoint

結論

如果你對教程有疑問,請在評論部分說明。

更新於: 2019-10-23

17K+ 瀏覽量

啟動您的 職業

透過完成課程來獲得認證

開始
廣告