在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 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短