在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
结论
如果您对本教程有疑问,请在评论部分中提及它们。
热门推荐
10 集体生日祝福语简短的
11 公司的祝福语简短2026
12 幼师离别祝福语老师简短
13 孩子语音婚礼祝福语简短
14 欢送退休人员简短祝福语
15 关于糖果的祝福语简短
16 朋友买新房祝福语简短
17 医美的祝福语大全简短
18 妈咪跟我生日祝福语简短