a shot of dev knowledge

RELATED TAGS

# 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 string
s = "this is an example"

print("Original string -> " + s)

#split the string where space is present
word_list = s.split(" ")

print("List of words after splitting -> " + str(word_list))

#reverse the list
reversed_list = list(reversed(word_list))

print("Reversed list of words -> " + str(reversed_list))

#join reversed list
reversed_str = " ".join(reversed_list)

print("Reversed String -> " + reversed_str)

### Explanation

In the following code snippet:

• Line 7: Split the original string s where the character space is present using the split(" ") method.
• Line 12: Reverse the list word_list with the function reversed(), 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 the join() method.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 