Program to swap string characters pairwise in Python

Suppose we have a string s. We have to swap all odd positioned elements with the even positioned elements. So finally we shall get a permutation of s where elements are pairwise swapped.

So, if the input is like s = "programming", then the output will be "rpgoarmmnig"

To solve this, we will follow these steps −

  • s := make a list from the characters of s
  • for i in range 0 to size of s - 1, increase by 2, do
    • swap s[i], s[i+1] with s[i+1], s[i]
  • join characters from s to make whole string and return


Let us see the following implementation to get better understanding −

def solve(s):
   s = list(s)
   for i in range(0, len(s)-1, 2):
      s[i], s[i+1] = s[i+1], s[i]

   return ''.join(s)

s = "programming"