Intern at Microsoft Sept. 3, 2020, 1:49 p.m. ⋅ 384 views

Reverse words in a given string

Let's take a string s,  we want to reverse its words. For example - 

Sample input 1

Hello HackersFriend

Sample output 1

HackersFriend Hello



Easiest way to implement it would be to split the string s and the reverse it. Here is implementation of this approach.

# Python3 program to reverse words of a string 
# s = input() 

s = "Hello HackersFriend"
words = s.split(' ') 

string =[] 

for word in words: 
	string.insert(0, word) 

print("Reversed String: ", end= '') 
print(" ".join(string))


HackersFriend Hello


You can also implement it using stacks. Initially you can push every word from beginning into stack then pop it out and print it. The reason why this approach would work is because, stack in LIFO (Last In First Out) Data structure, hence the word, which we will push at end would come first and so on.


Go back to feed

HackersFriend Updates

View more


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details

Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details