How to reverse words in a given string in Python
In this shot, we will look at how to reverse a string in Python. An example of what this entails is given below.
Example
Input: "this is an example"
Output: "example an is this"
Solution
We will use the in-built methods split(), join(), and reversed() to solve this problem.
split(): This method splits the given string into a list.reversed(): This function returns the list in reversed order.join(): This method joins the given list, with the provided string in-between them.
Algorithm
- First, split the given string, using
split()on the basis of the space" "character. - Reverse the list obtained from the
split()method. - Now, join the list obtained after reversing with the
join()method.
Code
#original strings = "this is an example"print("Original string -> " + s)#split the string where space is presentword_list = s.split(" ")print("List of words after splitting -> " + str(word_list))#reverse the listreversed_list = list(reversed(word_list))print("Reversed list of words -> " + str(reversed_list))#join reversed listreversed_str = " ".join(reversed_list)print("Reversed String -> " + reversed_str)
Explanation
In the following code snippet:
- Line 7: Split the original string
swhere the characterspaceis present using thesplit(" ")method. - Line 12: Reverse the list
word_listwith the functionreversed(), which returns a list iterator, and convert it into the list. - Line 17: Join the words present in the list with a character
space, using thejoin()method.