Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reverse words in a given String in Python
We are given a string, and our goal is to reverse all the words which are present in the string. We can use the split() method and reversed() function to achieve this. Let's see some sample test cases.
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
Python provides multiple approaches to reverse words in a string. Let's explore the most common methods.
Method 1: Using split() and reversed()
This approach splits the string into words and reverses the order using reversed() ?
# 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 result = " ".join(words) print(result)
programmer python a am I
Method 2: Using Slicing
We can use Python's slicing feature to reverse the list of words ?
# initializing the string string = "tutorialspoint is a educational website" # splitting and reversing using slicing words = string.split()[::-1] # joining the words result = " ".join(words) print(result)
website educational a is tutorialspoint
Method 3: One-line Solution
We can combine all operations in a single line for a more concise solution ?
# one-line solution string = "Python makes programming easy" result = " ".join(string.split()[::-1]) print(result)
easy programming makes Python
Algorithm
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 or slicing. 4. Join the words using the join() function and print the result.
Comparison
| Method | Readability | Memory Usage | Best For |
|---|---|---|---|
reversed() |
High | Creates iterator | Clear step-by-step approach |
Slicing [::-1]
|
Medium | Creates new list | Concise code |
| One-line | Low | Minimal | Quick solutions |
Conclusion
Use split()[::-1] for the most concise approach, or reversed(split()) for better readability. Both methods effectively reverse the order of words in a string by splitting on spaces and rejoining.
