Register for 45 Day Coding Challenge by CodeStudio And Win Some Exciting Prizes

# Python Program to Swap Characters in String

Python Program to Swap Characters in String | To Swap two characters in the string, there are several methods in the python library that makes the programmer easy to achieve his problem. Swapping characters in the string is just to exchange two characters in the given string.  As there is no swap method in python there is a need to define a swap() method. Hence we need to use a user-defined function to solve this problem.

To understand this problem more let us go through some examples:

``````string = "Python"
print(swap(3,1))``````

Output:- Phtyon

As in the above example, we can’t use the swap() method directly, so we would need to define a function and then exchange the elements.

## Python Program to Swap Characters in String

``````# Python program to swap two characters in string

def swap(str, i, j):
list1 = list(str)
list1[i], list1[j] = list1[j], list1[i]
return ''.join(list1)

string = "Know Program"
print(swap(string, 2, 6))``````

Output:

Knrw Poogram

The explanation for the above code goes as follows:-

Step1: First we define a method called swap() which takes one string parameter named str, and two integer parameters i and j, then we equate list1 = list(str) that is, this line converts the string to list then swaps the characters in the string by this logic list1[i], list1[j] = list[j], list1[i]. Now return the llist1.

Step2: Define the string and call the swap() method.

In the code, we have swapped two characters ‘o’ and ‘r’. We swapped these two characters by taking the string of the user’s choice that is by taking the input from the string.

## Python Program to Swap First and Last Character of String

``````# Python program to swap first and last character of string

def swap(str):
if len(str) <= 1:
return str
middle = str[1:len(str) - 1]
return str[len(str) - 1] + middle + str[0]

string = "know program"
print(swap(string))``````

Output:-

mnow prograk

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!