How to Reversing Words in a String in Python

0 min read 135 words

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')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts