Hackbright Code Challenges

Reverse Words

Reverse Words

Whiteboard

Harder

Challenge

Medium

Concepts

Strings, Loops

Download

reverse-words.zip

Solution

Reverse Words: Solution


In this challenge, you need to reverse a string, keeping the word themselves in order, and preserving exact spacing.

For example, for the string:

"   hello  kitty "

This should produce:

" kitty  hello   "

(Note that we keep the 3 spaces before hello, the two spaces between “hello” and “kitty” and the space after “kitty”.

As a simple case, an empty string returns an empty string:

>>> rev("")
''

A simple word is also the same:

>>> rev("hello")
'hello'

Here, we reverse the order of the words, preserving the space between:

>>> rev("hello world")
'world hello'

Here, we reverse the worlds, preserving space—so it it should start with the 3 spaces that came after world, etc:

>>> rev(" hello  world   ")
'   world  hello '

We’ve provided a file, reversewords.py, with a stub function:

def rev(s):
    """Reverse word-order in string, preserving spaces."""

Implement this.