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:
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
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 –
- Create a list from the string characters by using the
list()
constructor. - Swap the required characters in the list using their indices.
- 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
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.
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.
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 –
- Convert Python String to a List
- Python String Count – With Examples
- Swap Elements in a Python List with these Methods
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.