Reverse words in a given string in Python

In this tutorial, we will learn how to reverse words of a string given by the user in python. Before getting on to the actual code, let us learn some string methods.

split() method

As the name suggests, the split() method basically splits the string into a list. You can condition it based on separator and maximum splits you want it to do. Default separator is a white space and default maximum split value is -1 (i.e. all the times).¬† You can split at ‘,’, ‘:’, ‘#’, etc.

Syntax:

string.split(separator, max_split)

Example:

string = "codespeedy is the best"

print(string.split())

Output:

['codespeedy', 'is', 'the', 'best']

reverse() method

There are various ways to reverse a string like reversed() function, using [::-1] to print in the reversed order or using the reverse() method. Each one has it’s own usage, advantages and disadvantages. In this tutorial, we have used reverse() method which will directly reverse and modify the original list.

Syntax:




list.reverse()

Example:

list = ['1', '2', '3', '4']

print(list.reverse())

Output:

['4','3','2','1']

join() method

join() method simply concatenate iterable-object like the elements of list, tuple, string, etc. This function returns a string with all the elements joined by string separator.

Syntax:

string.join(element)

Example:

list = ['1', '2', '3', '4']

separator = '-'

print(separator.join(list))

Output:

1-2-3-4

Reversing words of a string in Python

Problem statement: Write a python program to reverse words of a given string.

Steps/Algorithm:

  1. Take the string input from user.
  2. Split the string using split() function.
  3. Use the reverse() method to reverse all the words that have been split from the string.
  4. Finally, join and print them using the join() function.

Code/Program:

x = input("Enter any string: ")
#take input from user

a = x.split()
#use split method to split at whitespaces

a.reverse()
#reverse all the elements of the string 

print(' '.join(a))
#concatenate them into a string

Output:

Enter any string: codespeedy is the best
best the is codespeedy

NOTE: There may be other possible ways to solve this problem.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *