
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
Example
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" print(solve(s))
Input
"programming"
Output
rpgoarmmnig
- Related Articles
- Java Program to Swap Pair of Characters
- Program to find Lexicographically Smallest String With One Swap in Python
- C++ Pairwise Swap Leaf Nodes in a Binary Tree
- Python Program to find mirror characters in a string
- Python Program to Capitalize repeated characters in a string
- Program to make pairwise adjacent sums small in Python
- Python program to find all duplicate characters in a string
- Concatenated string with uncommon characters in Python program
- C++ Pairwise Swap Elements of a Given Linked List
- Program to find string after removing consecutive duplicate characters in Python
- Python Program to Count Number of Lowercase Characters in a String
- Program to remove string characters which have occurred before in Python
- Program to remove duplicate characters from a given string in Python
- Java program to swap first and last characters of words in a sentence
- Python program to get all pairwise combinations from a list

Advertisements