How to Reverse Words in Python

The challenge

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples

"This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps"
Code language: Python (python)

The solution in Python code

Option 1:

def reverse_words(text): out = [] for word in text.split(" "): out.append(word[::-1]) return " ".join(out)
Code language: Python (python)

Option 2:

def reverse_words(str): return ' '.join(s[::-1] for s in str.split(' '))
Code language: Python (python)

Option 3:

def reverse_words(str): return " ".join(map(lambda word: word[::-1], str.split(' ')))
Code language: Python (python)

Test cases to validate our solution

import test from solution import reverse_words @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(reverse_words('The quick brown fox jumps over the lazy dog.'), 'ehT kciuq nworb xof spmuj revo eht yzal .god') test.assert_equals(reverse_words('apple'), 'elppa') test.assert_equals(reverse_words('a b c d'), 'a b c d') test.assert_equals(reverse_words('double spaced words'), 'elbuod decaps sdrow')
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments