Write a Python program to reverse words in a string


The program is written in Python and reverses the words in a given string. It first defines a string a and assigns it the value "Tutor Joes Computer Educations". Then, it uses a for loop to iterate over the lines in the string a. The split() method is used to split the string a into lines using the newline character \n as the separator. Since the string a does not contain any newline characters, the loop will only run once.

In each iteration, the split() method is used again to split the line into words using a space character as the separator. The join() method is then used to join the words in the reverse order, separated by a space character. The reverse order of the words is achieved using a slice [::-1], which returns a reversed copy of the list of words. Finally, the reversed words are displayed using the print() function.

Source Code

a = "Tutor Joes Computer Educations"
for line in a.split('\n'):
	print(' '.join(line.split()[::-1]))

Output

Educations Computer Joes Tutor


Example Programs