Skip to Content

Swap Adjacent Characters in a Python String with this Method

In this tutorial, we will look at how we can swap adjacent characters in a string. Let’s look at an example to better understand the task at hand.

Swapping adjacent characters example

swap adjacent characters in a python string

Let’s say you have the string, “heat”, after swapping the adjacent characters, the string becomes “ehta”. Here, we’re swapping the ith character in the string with the (i+1)th character. That is, h gets swapped with e and a gets swapped with t.

What if there are an odd number of characters in the string?

In that case, the last character doesn’t get swapped. For example, swapping adjacent characters in the string “cat” should result in “act”. Since we didn’t have a following adjacent character for t, it remains as it is.

Highlighted programs for you

Flatiron School

Flatiron School

Data Science Bootcamp
Product Design UX/UI Bootcamp

University of Maryland Global Campus

University of Maryland Global Campus

Cloud Computing Systems Master's
Digital Forensics & Cyber Investigation Master's

Creighton University

Creighton University

Health Informatics Master's

How to swap adjacent characters in a Python string?

Strings are immutable in Python, so once they are created, you cannot actually change the position of the characters inside a string. You can, however, create a new string with the required modifications.

To swap the adjacent characters in a string, use the following steps –

  1. Convert the string to a list (which is a mutable object in Python) of its characters using the list() function.
  2. Iterate through each pair of values starting from the left in the resulting list and swap them.
  3. Join the characters in the list together using the string join() function to get the string that has the adjacent characters from the original string removed.

The following is a function that implements the steps mentioned above.

# function to swap the adjacent characters in a string and return the new string
def swap_adjacent_chars(s):
    # create a list from string characters
    ls = list(s)
    # iterate through each pair of values in the list
    for i in range(0, len(ls)-1, 2):
        # swap the adjacent values
        ls[i], ls[i+1] = ls[i+1], ls[i]
    # join the characters in the list to get the result
    result = "".join(ls)
    return result

Here, we are using the range() function in Python to iterate through each pair of values in a list – notice that we’re using a step size of 2.

Examples

Let’s now look at some examples of using the above syntax, we’ll apply the function created above directly on some strings.

First, let’s take an example where the string has an even number of characters.

# create a string
s1 = "heat"
# swap the adjacent characters
res = swap_adjacent_chars(s1)
# display the result
print(res)

Output:


ehta

Note that you can reassign a variable (storing a string value) to a new value, so we could directly store the result from the swap_adjacent_chars() function if the original string is not required.

Let’s now take an example where the string has an odd number of characters.

# create a string
s2 = "cat"
# swap the adjacent characters
res = swap_adjacent_chars(s2)
# display the result
print(res)

Output:

act

The last character didn’t get swapped.

FAQs

How do you swap the adjacent characters in a string?

Convert the string to a list, iterate through each pair of values in the list from the left and swap them. Join the list elements back to get the resulting string.

What if the string has an odd number of characters?

In the string has an odd number of characters, then the last character in the string doesn’t get swapped.

You might also be interested in –



Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.