The given problem is simple. You get an input string that consists of multiple words. Your function’s expected output should reverse all the words in the given string, without any leading or trailing white spaces beside the ones between each word.
Input: "My name is alice" Expected output: "alice is name My"
Input: " hello world " Expected output: "world hello"
To find a solution it can often be of great help to split the problem into multiple very simple problems. In this case we got 3 major issues:
- Split the string into words
- Reverse the order
- Recreate the string
Each of these problems is pretty easy to solve, reducing the overall complexity to solve the whole problem drastically.
I commented on the following Python code, and it should be pretty self-explaining. If you have any problems understanding the code, please leave a comment, mail us or contact us via any of our social media channels.
Test the Solution
To test our solution we implement a brief function that tests if the resulting output fits the expected one:
Running the reverse_string.py file will lead to the following output:
Correct Output: alice is name My Correct Output: world hello
This closes my solution of “Reverse words in a string”. I hope you enjoyed reading it, as it was the first post of our new category. If you have any suggestions for improvement, we’d be happy to hear from you!
I am a computer scientist and entrepreneur from Germany. I chose to work in computer science because I love building things and improve people’s lives.
Our Book Recommendations on Python (Affiliate)