We will develop a program to reverse words in a string python. In this article, we are using the split(), reversed(), and join() functions to reverse the words of a string in Python. The split() method splits the string from the specified separator and returns a list object with string elements.
The reversed() function allows us to process the items in a sequence in reverse order. It accepts a sequence and returns an iterator. The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
Example of reverse words in a string:-
String: Know Program is best to learn programming
Reverse: programming learn to best is Program Know
Python Program to Reverse Words in a String
We will take a string while declaring the variables. Then, find the reverse of words in a string using reversed() function. Finally, the result will be displayed on the screen.
# Python program to reverse words in a string
# take inputs
string = 'Know Program'
# splitting the string into list of words
words = string.split(' ')
# reversing the split string list and join using space
reverseString = " ".join(reversed(words))
# print reverse of each word in a string
print('The reverse is', reverseString)
Output:-
The reverse is Program Know
Reverse Words in a String Python
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse words in a string
# take inputs
string = input('Enter the string: ')
# splitting the string into list of words
words = string.split(' ')
# reversing the split string list and join using space
reverseString = " ".join(reversed(words))
# print reverse of each word in a string
print('The reverse is', reverseString)
Output for the input values test-case-1:-
Enter the string: Welcome to Know Program
The reverse is Program Know to Welcome
Output for the input values test-case-2:-
Enter the string: Reverse words of a string
The reverse is string a of words Reverse
Reverse Words in a String Python using Function
We can also take the help of a function to reverse words in a string. A function is a block of code that performs a specific task.
# Python program to reverse words in a string
def reverseWords(s): #user-defined function
# splitting the string into list of words
words = string.split(' ')
# reversing the split string list and join using space
reverse = " ".join(reversed(words))
return reverse
# take inputs
string = input('Enter the string: ')
# calling function and display result
print('The reverse is', reverseWords(string))
Output for the input values test-case-1:-
Enter the string: My Name is Guddu Kumar Singh
The reverse is Singh Kumar Guddu is Name My
Output for the input values test-case-2:-
Enter the string: Know Program is best to learn programming
The reverse is programming learn to best is Program Know
Also See:- Reverse Each Word in a String Python