用 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
结论
如果你对教程有疑问,请在评论部分说明。
广告