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"
Code language: JavaScript (javascript)

The solution in Python code

Option 1:

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

Option 2:

def reverse(st): return " ".join(reversed(st.split())).strip()
Code language: Python (python)

Option 3:

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

Option 4:

def reverse(st): st = st.split() st.reverse() return ' '.join(st)
Code language: Python (python)

Test cases to validate our solution

import test from solution import reverse @test.describe("Fixed Tests") def fixed_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(reverse('Hello World'), 'World Hello') test.assert_equals(reverse('Hi There.'), 'There. Hi')
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments