Register Login

How to Reverse Words in a String Python

Updated Jan 08, 2020

In this article, you will learn, In python, how to reverse the order of the words in the string. Please keep in mind that here we are not reversing the character.

Example:

# Program to explain reverse Word in String or Sentence
# Using for split() function

# Define a function
def reverse_word(string):
    # Split string with blank space
    # And convert to list
    rlist=string.split()

    # Reverse list using reverse function
    rlist.reverse()

    # Convert list to string with space
    return " ".join(rlist)

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_word(string))

Output: 

Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This

Explanation:

In the above example, first, we are converting a string to the list using the split() function, then reversing the order of the list using a reverse() function and converting backlist to the string using join() method.

Using Slicing

Example:

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print('Original : ', string)
print('Reverse : ', " ".join(string.split()[::-1]))

Output: 

Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This

Explanation:

Above example executes in the following three steps:

1. Split the string in words using split()

2. Reverse the words Slice

3. Join words with join()


×