Learn about Reversing Words in a String Python.
We are given a string as an input in Python, and our task is to reverse words present in the string. We will use different string functions in Python to complete the program. In Python, a string is created by putting a stream of characters inside single quotes, double quotes, or triple quotes.
Reverse words in a string mean that we have to reverse the position of all words in the given string. Let us look at some examples : Input: Hello World
Output: World Hello
Input: I love Programming
Output: Programming love I
The intuition of this approach is to first reverse every
word present in the string individually, For Example : Overview
Scope
How To Reverse Words In A String Python ?
Examples
Method - 1 : Reverse The Individual Words And Then Reverse The Whole String
I like coding becomes, I ekil gnidoc. Now, we have to reverse the whole string to get the desired result which in the case of this example will be coding like I.
Let us now see the implementation of this approach to reverse words in a string in Python :
def reverseWord(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start = start + 1 end = end - 1 s = "I love Programming" # convert string to a list of characters s = list(s) # to keep track of where each word starts start = 0 while True: try: # find space end = s.index(' ', start) # Call reverseWord for each word reverseWord(s, start, end - 1) #update start variable start = end + 1 # for the last word in string ValueError is returned except ValueError: # reverse the last word reverseWord(s, start, len(s) - 1) break # reverse the entire list s.reverse() # convert the character list back to string s = "".join(s) print(s)
Output :
Complexity analysis
Since we are traversing the whole string once to reverse the words in a string, the Time Complexity is O(n)O(n), where nn is the size of the string.
While an auxiliary space is required to reverse words in a string, the Space Complexity is O(n)O(n), where nn is the size of the string.
Method - 2 : By Splitting The String Using The split() Function In Python
The above-discussed method does not handle the case when the string starts with a space. Therefore, we will now discuss an approach that uses Python's in-built split() function. The algorithm to implement this method is as follows :
- Define a function that will take a string as input.
- Split the input string on space using the split() function and store the result in the form of a list.
- Reverse the created list using the reversed() function and add them to a new string using the join() string function in Python.
- Return the new string
Let us now see the implementation of this approach to reverse words in a string in Python :
def reverseWords(s): words = s.split(' ') reverse_str = ' '.join(reversed(words)) return reverse_str s1 = "I love Programming" print (reverseWords(s1))
Output :
The built-in reversed() function in Python returns an iterator object rather than an entire list.
Complexity analysis
Since we are traversing the whole string to split it in space, the Time Complexity is O(n)O(n) , where nn is the size of the string.
While an auxiliary space is required to store the string in a reverse manner, the Space Complexity is O(n)O(n) , where nn is the size of the string.
Now we will discuss an optimal approach to reverse words in a string Python, the intuition of this approach is to swap the words of the string from the beginning and end, using a two-pointer approach, to reverse the string in constant space.
The algorithm is demonstrated as follows :
- Convert the string into an array of strings, by splitting it on space.
- Initialize the two pointers left and right to 0 and len(string) – 1 respectively.
- While the left pointer does not exceed the right pointer, swap the elements at the left and right pointer, move the left pointer forward and the right pointer backward by 1 step.
- Finally, return the final reversed string.
Let us now see the implementation of this approach to reverse words in a string in Python :
def reverseWords(s): # splitting the string s = s.split(" ") # initializing 2 pointers left = 0 right = len(s) - 1 # traversing till left does not exceed right pointer while left <= right: # swap elements s[left], s[right] = s[right], s[left] # increment left and decrement right left += 1 right -= 1 s = " ".join(s) return s s = 'I love Programming' print(reverseWords(s))
Output :
Complexity analysis
Since we are traversing the whole string to split it in space, the Time Complexity is O(n)O(n), where nn is the size of the string.
While an auxiliary space is required to store the string in a reverse manner, the Space Complexity is O(1)O(1).
Learn More
To study in-depth about the split function in Python please refer here.
To learn more about the join function in Python check this article.
Conclusion
- In this article, we have used Python built-in string functions like split(), reversed(), and join() in our program to reverse words in a string.
- The Optimal Approach for the program has the Time Complexity O(n )O(n) and Space Complexity O(1)O(1) .
- You can try solving this problem with the help of Regular Expressions also.