How Can We Help?
Swapping the string is one of the most commonly used operations by programmers. The string is a data type to store the text documents enclosed within quotes. This article will explain how to swap string characters in python using different techniques as follows.
- Swap Characters in String using Indexing
- Swap Characters in String using List
- Characters in String using built-In Function
Swapping Character in String Through Indexing
This is a trendy yet fundamental method used by programmers. The algorithm we follow is as follows:
- First, define the index of the numbers you want to swap in the string. Let us assume that we have two indexes for two characters, namely x and y.
- Next, use another empty string and construct the new string from the old string. First, slice the characters up to index x and then append the character at the index of y. Next, append the characters from x+1 to y(y excluded). Next, append the character previously at the yth index of the old string. Finally, append all the rest of the characters.
You can see we only need the knowledge of indexing here to use this algorithm.
Example (1)
def swap_characters(string, l, r):
ans = ""
ans = string[0:l] + string[r] + string[l+1:r] + string[l] + string[r+1:]
return ans
string = input("Enter the string: ")
first_index = int(
input("Enter the index of first character that you need to swap: "))
second_index = int(
input("Enter the index of second character that you need to swap: "))
print(f"The entered string is: {string}")
print(f"The entered the first index is: {first_index}")
print(f"The entered second index is: {second_index}")
print(swap_characters(string, first_index, second_index))
Output:
The entered string is: python
The entered the first index is: 2
The entered second index is: 3
‘Pyhton’
Explanation:
- First, we defined a function named swap_characters. This nonvoid function takes three arguments, namely string,l, and r.
- Next, we initialized an empty string under this function, namely ans.
- We first sliced the string to the index l and appended r into it. Next, we sliced from index i+1 to r and added it into the string a. Next, we again appended the character at the index l and added it to the ans string. Finally, we added the rest of the characters of the string into the ans string.
- We returned the ans variable. We took the value of the string from the users with the help of the input function.
- Next, we also took the index of the characters we wanted to stop from the user using the input function of python.
- We printed the values using the print statement and finally called the swap_characters function with appropriate parameters.
Class-based implementation of the above approach is as follows:
Example (2)
class Swap:
def __init__(self, string, x, y):
self.text = string
self.x = x
self.y = y
def swap_characters(self):
ans = ""
ans = self.text[0:self.x] + self.text[self.y] + self.text[self.x +
1:self.y] + self.text[self.x] + self.text[self.y+1:]
return ans
string = input("Enter the string: ")
first_index = int(
input("Enter the index of first character that you need to swap: "))
second_index = int(
input("Enter the index of second character that you need to swap: "))
print(f"The entered string is: {string}")
print(f"The entered first character index is: {first_index}")
print(f"The entered second character index is: {second_index}")
swap = Swap(string, first_index, second_index)
print(swap.swap_characters())
Output:
The entered string is: solidity
The entered first character index is: 2
The entered second character index is: 3
Soildity
We can slightly tweak the above algorithm and modify it as follows:
Example (3)
def swap_characters(string, l, r):
ans = ""
ans = string[0:l] + string[r] + string[l+1:r] + string[l] + string[r+1:]
return ans
string = input("Enter the string: ")
first_char= input("Enter the index of first character that you need to swap: ")
second_char = input("Enter the index of second character that you need to swap: ")
first_index=string.find(first_char)
second_index=string.find(second_char)
print(f"The entered string is: {string}")
print(f"The entered first character is: {first_char}")
print(f"The entered second character is: {second_char}")
print(swap_characters(string, first_index, second_index))
Output:
The entered string is: python
The entered the first character is: t
The entered the second character is: h
‘Python’
We took the character as inputs in the above code instead of the index. Before we called the swap_characters function, we used the find function of python to fetch the index of the character in the string. After that, we called the function.
Using List to Swap Characters in String
We know that lists in python are mutable data types. We can use this property to swap the character in the string. We can implement the below approach for the same:
- First, we need to convert the string into a list using the list function of python.
- Next, we can use the mutability property of the list to swap the characters.
- Next, initialize an empty string and iterate through the list element. With each iteration, append the element of the list into the string.
Example (4)
def swap_characters(string, x,y):
lst=list(string)
lst[x]=string[y]
lst[y]=string[x]
ans=""
for i in lst:
ans=ans+i
return ans
string = input("Enter the string: ")
first_char= input("Enter the index of first character that you need to swap: ")
second_char = input("Enter the index of second character that you need to swap: ")
first_index=string.find(first_char)
second_index=string.find(second_char)
print(f"The entered string is: {string}")
print(f"The entered first character is: {first_char}")
print(f"The entered second character is: {second_char}")
print(swap_characters(string, first_index, second_index))
Output:
The entered string is: string
The entered the first character is: t
The entered the second character is: i
‘sirtng ‘
Explanation:
- First, we created a function named swap_characters. This is a nonvoid function that takes three arguments, namely string, x, and y.
- Under this function, we first converted the string into a list data type using the list function of python.
- Next, we used the mutability property of the list and swapped the elements.
- We initialized another empty string named ans. We iterated through the list and added the element into the string “ans”. Finally, we returned the string.
- We took all the inputs from the users using the input function of python. We called the swap_characters with appropriate arguments to get our result.
Using Python built-In Function to Swap Characters in String
Python also has its built-in function to swap characters in the string. It is the replacement function that takes three arguments. The first argument is the string we need to swap the element. The second argument is the character we need to swap, and the third is the character we need to swap the first character.
Example (5)
def swap_function(text, ch1, ch2):
text = text.replace(ch2, '!',)
text = text.replace(ch1, ch2)
text = text.replace('!', ch1)
return text
string = input("Enter the string: ")
first_char= input("Enter the index of first character that you need to swap: ")
second_char = input("Enter the index of second character that you need to swap: ")
printf("The entered string is: {string}")
printf("The entered first character is: {first_char}")
print(f"The entered second character is: {second_char}")
print(swap_function(string,first_char,second_char))
Output:
The entered string is: abcdef
The entered the first character is: c
The entered the second character is: f
‘Abfdec’
Class-based implementation of the above approach is as follows:
Example (6)
class Swap:
def __init__(self, string, ch1, ch2):
self.text = string
self.ch1 = ch1
self.ch2 = ch2
def swap_function(self):
self.text = self.text.replace(self.ch2, '!',)
self.text = self.text.replace(self.ch1, self.ch2)
self.text = self.text.replace('!', self.ch1)
return self.text
string = input("Enter the string: ")
first_char = input(
"Enter the index of the first character that you need to swap: ")
second_char = input(
"Enter the index of the second character that you need to swap: ")
print(f"The entered string is: {string}")
print(f"The entered first character is: {first_char}")
print(f"The entered second character is: {second_char}")
swap = Swap(string, first_char, second_char)
print(swap.swap_function())
Output:
The entered string is: string
The entered the first character is: t
The entered the second character is: r
‘string’
Conclusion
This article taught us how to swap the string characters using different methods. We first saw how to swap the string characters using a custom-defined function. Next, we learned how to use the python inbuild function to swap the string characters. The most efficient approach among all the methods we discussed is to use the replace function.
We recommend that readers try to code on this concept to understand the topic better.