在Python中反转给定字符串中的单词
给我们一个字符串,我们的目标是反转字符串中出现的所有单词。我们可以使用split方法和反向函数来实现输出。让我们看一些示例测试用例。
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
结论
如果您对本教程有疑问,请在评论部分中提及它们。