- Swap Characters in a Python String with this Method
- Can you change characters in a Python string in place?
- How to create a new string with the required characters swapped?
- Example – Swap string characters using a list
- Example – Swap the first and last characters
- How is swapping characters different from replacing characters in a String?
- FAQs
- Author
- How do you swap two strings in python?
- How can I swap two strings without using the third string?
- How do you swap two variables?
- How do you split a string into two equal parts?
- Popular
- Pages
- Privacy Overview
- Python Program to Swap Two Strings
- Swap Two Strings in Python
- Same Program in Other Languages
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.
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 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.
# create a string name = "Tim" # you cannot modify the string name[0] = "J" # this will give an error
--------------------------------------------------------------------------- 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 .
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)
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)
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)
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"))
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.
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 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. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
How do you swap two strings in python?
How can I swap two strings without using the third string?
How do you swap two string variables without using third or temp variable in java?
How do you swap words in Python?
Join the words using the join function and print it….Algorithm
- Initialize the string.
- Split the string on space and store the resultant list in a variable called words.
- Reverse the list words using reversed function.
- Convert the result to list.
Is there a swap function in Python?
In Python, you can easily swap values without temp (temporary variable). It is possible to swap values of variables and to swap values (elements) in a list.
How do you swap two variables?
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010).
How do you split a string into two equal parts?
- STEP 1: START.
- STEP 2: DEFINE str = “aaaabbbbcccc”
- STEP 3: DEFINE len.
- STEP 4: SET n =3.
- STEP 5: SET temp = 0.
- STEP 6: chars = len/n.
- STEP 7: DEFINE String[] equalstr.
- STEP 8: IF (len\%n!=0) then PRINT (“String can’t be divided into equal parts”) else go to STEP 9.
How do you swap items in a list in Python?
Use multiple assignment to swap the value at each index in the list.
- a_list = [“a”, “b”, “c”]
- index1 = a_list. index(“a”)
- index2 = a_list. index(“c”)
- a_list[index1], a_list[index2] = a_list[index2], a_list[index1]
- print(a_list)
How do I swap a list in Python?
Popular
Pages
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie | Duration | Description |
---|---|---|
cookielawinfo-checkbox-analytics | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Analytics». |
cookielawinfo-checkbox-functional | 11 months | The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category «Functional». |
cookielawinfo-checkbox-necessary | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category «Necessary». |
cookielawinfo-checkbox-others | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Other. |
cookielawinfo-checkbox-performance | 11 months | This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Performance». |
viewed_cookie_policy | 11 months | The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data. |
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
Python Program to Swap Two Strings
This article covers a program in Python, that swaps two strings, entered by user at run-time of the program.
Swap Two Strings in Python
The question is, write a Python program to swap two given strings. The program given below is its answer:
print("Enter the First String: ", end="") string1 = input() print("Enter the Second String: ", end="") string2 = input() print("\nString before swap:") print("string1 blue">print("string2 blue">print("\nString after swap:") print("string1 blue">print("string2 img_box">