How to Reversing Words in a String in Python


The challenge

Write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:

As the input may have trailing spaces, you will also need to ignore unnecessary whitespace.

Example (Input –> Output)

"Hello World" --> "World Hello"
"Hi There." --> "There. Hi"

The solution in Python code

Option 1:

import re

def reverse(st):
    return " ".join(re.sub('\s+', ' ', st).strip().split(" ")[::-1])

Option 2:

def reverse(st):
    return " ".join(reversed(st.split())).strip()

Option 3:

def reverse(st):
    s = st.split()
    return ' '.join(s[::-1])

Option 4:

def reverse(st):
    st = st.split()
    st.reverse()
    return ' '.join(st)

Test cases to validate our solution

import test
from solution import reverse

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():
        test.assert_equals(reverse('Hello World'), 'World Hello')
        test.assert_equals(reverse('Hi There.'), 'There. Hi')