Swapping two characters in a string in Python can seem complex at first because strings in Python are immutable.
This means that once a string is created, it cannot be changed. However, Python offers a variety of methods that can create a new string with desired changes.
This tutorial will walk you through the process of swapping two characters of a string using Python.
Step 1: Accessing Characters in a String
In Python, the characters of a string can be accessed using their index. The index of a string starts from 0 and goes up to the length of the string minus one. For instance, in the string “PYTHON”, the index of “P” is 0, “Y” is 1, and so on. We can use these indexes to access individual characters or a range of characters in a string.
1 2 3 |
str = "PYTHON" print(str[0]) print(str[1:4]) |
You should get the following output:
P YTH
Step 2: Swapping the Characters
Since strings are immutable in Python, we cannot directly replace characters of a string by index. However, we can convert the string to a list, swap the characters in the list, and then join the list back into a string.
1 2 3 4 5 |
str = "PYTHON" str_list = list(str) str_list[1], str_list[4] = str_list[4], str_list[1] new_str = ''.join(str_list) print(new_str) |
You should get the following output:
PTOHN
In this case, we have swapped ‘Y’ and ‘O’ in the string “PYTHON”.
Step 3: Making a Function for This Operation
To make our code reusable, we can define a function that takes a string and the indexes of two characters to be swapped as parameters and returns the string after swapping the two characters.
1 2 3 4 5 6 |
def swap_chars(str, i, j): str_list = list(str) str_list[i], str_list[j] = str_list[j], str_list[i] return ''.join(str_list) print(swap_chars("PYTHON", 0, 5)) |
You should get the following output:
NYTHOP
Full Code
1 2 3 4 5 6 |
def swap_chars(str, i, j): str_list = list(str) str_list[i], str_list[j] = str_list[j], str_list[i] return ''.join(str_list) print(swap_chars("PYTHON", 0, 5)) |
Conclusion
In this tutorial, we learned that although strings in Python are immutable, we can still swap two characters in a string by converting the string to a list, swapping the characters in the list, and then converting the list back to a string. We also learned how to make our code reusable by defining a function for this operation.
Python offers a variety of string methods that can be used to perform different operations on strings. To learn more about these methods, you can visit the official Python documentation.