Thursday, 9 February 2017

Python Program for Reversing the order of the words in a String

Python Program for Reversing the order of the words in a String is given below. In this program, t is the number of test cases.

PROGRAM:
t=int(input())              # t is the tes cases
for i in range(0,t):
    string=raw_input()    #string is the first input
    word=""
    listing=[]                #declaring the empty list
    k=0
    for j in range(0,len(string)):
        if(string[j]==" "):
            listing.insert(k,word)
            k=k+1
            word=""
        elif(j==len(string)-1):
            word=word+string[j]
            listing.insert(k,word)
        else:
            word=word+string[j]
    listing.reverse()
    string=""
    for j in range(0,len(listing)):
        for k in range(0,len(listing[j])):
            if(k==len(listing[j])-1):
                string=string+listing[j][k]
                if(j<len(listing)-1):
                    string=string+" "
            else:
                string=string+listing[j][k]
    print(string)
    print("\n")

OUTPUT:


EmoticonEmoticon