Python Program to Reverse Words in a Given String in Python
In this tutorial, we will learn to reverse words in a given string in Python. Strings in Python are a sequence of characters. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. Reversing words in a string means we have to reverse the position of all the words in that particular string.
For example, a string "Welcome to StudyTonight" should be reversed to "StudyTonight to Welcome".
Look at the sample input and output of the program.
Input: hello world
Output: world hello
To reverse words in the string first, we have to separate out the words in the string and then reverse the words individually. We will be using the split() function which will automatically separate the words. We will then add these words to the new string in a reversed order.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Define a function that will accept the string and reverse the words in the string
Step 2- In the function, first separate out the words using split()
Step 3- Now reverse the words and add them to a new string
Step 4- Return the new string
Python Program
In our program, we have used reversed() to get the iterator that accesses the given sequence in the reverse order. And to add the words in the new string, we have used join() which will join all the words with a space in the new string.
def rev_words(string):
words = string.split(' ')
rev = ' '.join(reversed(words))
return rev
s= "Python is good"
print ("reverse: ",rev_words(s))
s2= "Hello from Study tonight"
print ("reverse: ",rev_words(s2))
reverse: good is Python
reverse: tonight Study from Hello
Conclusion
In this tutorial, we have discussed how to reverse the words of a string in Python. We have used built-in string functions like split(), reversed() and join() in our program. The use of each function is discussed properly above.