Swap even and odd characters in a string Python

  • by

Here in this page I have written a python code which will swap even and odd characters in a string. So, let’s get started. Before we begin, take a look the following code. I have not included any library here. I have written it out of basic python libraries.


str = 'CloudiKnow'
output = ''
i = 0
while i < len(str):
        if i + 1 < len(str):
                output = output + str[i + 1]
                output = output + str[i]
        i = i + 2
print 'Given   String: ' + str
print 'Swapped String: ' + output


Given   String: CloudiKnow
Swapped String: lCuoidnKwo

Code Explanation

I have taken a string as ‘str’. Then to generate output, I have given an another empty string. In the ‘for’ loop I will be iterating through 0 to the length of string ‘str’. I have an ‘if’ condition to check if the first character that we are taking has an adjacent character or not. If we do not have an adjacent character then we will skip it.

If we have an adjacent character then we will place that character at the beginning of the output and then the current character at the next position of output.

This will be looped till we have any characters left in the string. Once the loop is completed then the output will be printed along with the given string to compare. You can have a look at the output which I have given in the above immediately after the code.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

We are sorry that this post was not useful for you!

Let us improve this post!


Leave a Reply

Welcome to CloudiKnow.com blog, a platform to share knowledge and solution experience related to public cloud is base design of this site.

You can start the cloud journey right from here!
Please bookmark this page by pressing simply CTRL+D.