Reverse Parts Of A String

 Write a program to take input a line from stdin. You have to reverse every word of this line, except for the starting and ending line of the words. For example, for the following input:

we love coding in this world

the output is:

we lveo cnidog in tihs wlrod
  • every word has been reversed except it's first and last alphabet.

Input format:

  • first line contains the number of lines, n
  • this is followed by n lines

Output:

  • print each line such that the words are reversed as per the criteria above
Example Input:
5
hello all
this is a good
example
to show you how to reverse
a string

Output:
hlleo all 
tihs is a good 
elpmaxe 
to sohw you how to rsrevee 
a snirtg 





Solution:

t=int(input())
for i in range(t):
    s=input()
    str=s.split()
    for i in str:
        q=[h for h in i]  # for each word to be read
        k=1  #for 2nd character of word 
        j=len(i)-2  #for last but one char of word
        while(k<j):
            q[k],q[j]=q[j],q[k]   #swaping 
            k=k+1
            j=j-1
        print("".join(q),end=" ")
    print()



Comments

Popular posts from this blog

Right Arrow Pattern

Efficient Janitor

X Pattern