Reverse words in a given String in Python

PythonServer Side ProgrammingProgramming

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 the output. 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

Let's follow the below steps to achieve our goal.

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.
4. Convert the result to list.
5. Join the words using the join function and print it.

See the code for the above algorithm.

Example

 Live Demo

## 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))

Output

If you run the above program, you will get the following output.

programmer python a am I

Let's execute the code once again for different input.

Example

 Live Demo

## 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))

Output

If you run the above program, you will get the following output.

website educational a is tutorialspoint

Conclusion

If you have doubts regarding the tutorial, mention them in the comment section.

raja
Published on 23-Oct-2019 06:48:45
Advertisements