Skip to Content

Swap Characters in a Python String with this Method

In this tutorial, we will look at how to swap two characters in a Python string with the help of some examples.

Can you change characters in a Python string in place?

No. Strings in Python are immutable so you cannot modify a string after it has been created, you can, however, create a new string with the modified value and assign it to the original variable.

For example –

# create a string
name = "Tim"
# you cannot modify the string
name[0] = "J" # this will give an error

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[2], line 4
      2 name = "Tim"
      3 # you cannot modify the string
----> 4 name[0] = "J" # this will give an error

TypeError: 'str' object does not support item assignment

Get the memory location of the variable name.

id(name)

Output:

4572429488

Let’s reassign the value to the variable name with a different value.

# reassign the value to name
name = "Jim"
# show memory location
id(name)

Output:

4572563824

You can see that we cannot modify a string since it’s immutable. You can, however, create a new string and assign it the same variable (notice that the memory location of name after this operation is different from before).

Thus, to swap characters in a string, you’ll have to create a new string with the swapped characters.

How to create a new string with the required characters swapped?

You can use a list to swap characters in a string. Lists in Python are mutable. Use the list() constructor to get a list of individual characters in a string and then swap the characters by their indices using the following syntax –

# create a list from string characters
ls = list(s)
# swap the values at indices i and j
ls[i], ls[j] = ls[j], ls[i]
# create a new string with the swapped characters
s = "".join(ls)

In the above code, we take the following steps –

  1. Create a list from the string characters by using the list() constructor.
  2. Swap the required characters in the list using their indices.
  3. Join the list values into a new string and assign it to the original string variable (you can assign it to a new variable if you want to keep the original value).

Note that swapping two characters in a string is different from replacing a character with another character (see the detailed example below).

Let’s now look at some use cases of swapping string characters with the help of some examples.

Example – Swap string characters using a list

Let’s say we have a string and we want to swap the characters at the i and j indices.

# create a string
s = "batman"
# create a list from string
ls = list(s)
# indices of values to swap
i = 0
j = 2
# swap the values
ls[i], ls[j] = ls[j], ls[i]
# join the list characters into a new string
s = "".join(ls)
# display the string
print(s)

Output:

tabman

Here, we swap the characters at the indices 0 and 2 in the string “batman”. Note that the resulting string is a new string, “tabman”.

Example – Swap the first and last characters

We can use the above syntax to swap two characters at any index. To swap the first and the last values, use the index 0 (for the first element) and length-1 (for the last element).

# create a string
s = "batman"
# create a list from string
ls = list(s)
# indices of values to swap
i = 0
j = len(ls)-1
# swap the values
ls[i], ls[j] = ls[j], ls[i]
# join the list characters into a new string
s = "".join(ls)
# display the string
print(s)

Output:

natmab

The first and the last characters have been swapped.

How is swapping characters different from replacing characters in a String?

When swapping characters, we’re simply exchanging the position of two characters (both of which are in the string). Replacing a character with another character simply means replacing one (or more) occurrences of a character with a new character whether or not the new character is originally present in the string.

In one of the examples above, we swapped the characters “b” and “t” in the string “batman”. Now, if you want to replace, let’s say “b” with “c” (a character that is not present) in the word “batman”, you can do so using the Python string replace() function, which returns a new string with the replaced characters.

# replace "b" with "c"
s = "batman"
print(s.replace("b", "c"))

Output:

catman

We get “catman” by replacing “b” with “c”.

FAQs

Is it possible to directly swap two characters in a string?

No. Strings are immutable in Python and thus cannot be modified once they are created. You can, however, create a new string with the characters swapped using a list.

How can I swap two characters in a string in Python?

You can convert the string to a list of characters, then use the list indexing to swap values in the list at the required indices. You can then convert the list of characters to a string using the string join() function.

Can I use the replace() method to swap two characters in a string?

No, the replace() method replaces a specific character or substring with another character or substring, this is different from swapping (or exchanging the position) of two characters that are present in the string.

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. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.