Thursday 13 August 2020

Reverse order of words in a string

 

 

Sample Input: Hello everyone ! Welcome to MV's Code Guide

Output: Guide Code MV's to Welcome ! everyone Hello

Using Slice operator:

1
2
3
4
5
6
7
8
string_data=input("Enter a string: ")
list1=string_data.split()
#Using Slice Operator to reverse the items of list1
list2=list1[::-1]
# Using join() to form a string from items of list2 
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

 Using While loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
string_data=input("Enter a string: ")
list1=string_data.split()
print(list1)
list2=[]
i=len(list1)-1
while i>=0:
	list2.append(list1[i])
	i=i-1
print(list2)
result=" ".join(list2)
print("The string you entered:", string_data, sep="\n")
print("The result after reversing order of words in the string: ", result, sep="\n")

No comments:

Post a Comment