
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements