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.
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.
string = "codespeedy is the best" print(string.split())
['codespeedy', 'is', 'the', 'best']
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.
list = ['1', '2', '3', '4'] print(list.reverse())
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.
list = ['1', '2', '3', '4'] separator = '-' print(separator.join(list))
Reversing words of a string in Python
Problem statement: Write a python program to reverse words of a given string.
- Take the string input from user.
- Split the string using split() function.
- Use the reverse() method to reverse all the words that have been split from the string.
- Finally, join and print them using the join() function.
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
Enter any string: codespeedy is the best best the is codespeedy
NOTE: There may be other possible ways to solve this problem.