Program to swap string characters pairwise in Python

Swapping string characters pairwise means exchanging adjacent characters at positions (0,1), (2,3), (4,5), and so on. This is useful for simple text transformations and encoding operations.

Problem Statement

Given a string, swap all odd positioned elements with even positioned elements to create a pairwise swapped permutation.

For example, if the input is s = "programming", the output will be "rpgoarmmnig".

Algorithm

To solve this problem, we follow these steps ?

  • Convert the string to a list of characters
  • Iterate through the string with step size 2
  • Swap each pair of adjacent characters: s[i] with s[i+1]
  • Join the characters back into a string and return

Example

Let us see the 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"
print(solve(s))
rpgoarmmnig

How It Works

The algorithm processes the string "programming" as follows:

  • Position 0,1: 'p','r' ? 'r','p'
  • Position 2,3: 'o','g' ? 'g','o'
  • Position 4,5: 'r','a' ? 'a','r'
  • Position 6,7: 'm','m' ? 'm','m' (no change)
  • Position 8,9: 'i','n' ? 'n','i'
  • Position 10: 'g' remains unchanged (odd length)

Alternative Approach Using String Slicing

Here's a more concise solution using string slicing ?

def solve_slicing(s):
    result = ""
    for i in range(0, len(s)-1, 2):
        result += s[i+1] + s[i]
    
    # Add remaining character if string length is odd
    if len(s) % 2 == 1:
        result += s[-1]
    
    return result

s = "programming"
print(solve_slicing(s))

# Test with odd length string
s2 = "hello"
print(solve_slicing(s2))
rpgoarmmnig
ehllo

Conclusion

Pairwise character swapping can be efficiently implemented by converting the string to a list and swapping adjacent elements. The algorithm handles both even and odd length strings correctly, leaving the last character unchanged when the string length is odd.

Updated on: 2026-03-26T15:42:15+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements