Practice Python

Beginner Python exercises

28 May 2014

Reverse Word Order Solutions

Exercise 15

Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string:

  My name is Michele

Then I would see the string:

  Michele is name My

shown back to me.

Sample solution

Here is the quick, one-liner solution to the problem:

def reverseWord(w):
return ' '.join(w.split()[::-1])
view raw reverse_word hosted with ❤ by GitHub

But most likely you didn’t come up with that solution right away. You most likely went through a number of iterations like this:

# Exercise 14
# Write a function that asks the user for a string containing multiple words. Print
# back to the user the same string, except with the words in backwards order.
# method 1: loop through the words and insert each word at the begining of the result list
def reverse_v1(x):
y = x.split()
result = []
for word in y:
result.insert(0,word)
return " ".join(result)
# method 2
def reverse_v2(x):
y = x.split()
return " ".join(y[::-1])
# method 3
def reverse_v3(x):
y = x.split()
return " ".join(reversed(y))
# method 4
def reverse_v4(x):
y = x.split()
y.reverse()
return " ".join(y)
# test code
test1 = raw_input("Enter a sentence: ")
print reverse_v1(test1)
print reverse_v2(test1)
print reverse_v3(test1)
print reverse_v4(test1)
view raw Ex14 hosted with ❤ by GitHub

But you also could have taken a hybrid approach:

Enjoying Practice Python?


Explore Yubico
Explore Yubico