Strings in Python are just sequence of characters, but these are immutable meaning once created cannot be changed. For example – A string “ComputerScienceHub” once created in the program, characters cannot be changed turning “ComputerScienceHub” to “Computer1425Science” would raise an Error.
So characters of a string cannot be changed, but what if you have to change Characters in String?
Swapping Characters in Python String
Best approach to change characters in a string is to first convert it to a List, swap characters in list then again convert list to string.This is simplest algorithmic approach for swapping characters in a Python String.
Python Code for Swapping Characters in a String
# Swapping Characters in a Python String
x = "Computer"
# Swapping character at position 0(C) with character at position 4(u)
list_of_string_x = list(x)
# Swapping Elements at position 0 with element at position 4 in List
list_of_string_x[0], list_of_string_x[4] = list_of_string_x[4], list_of_string_x[0]
# Converting List Back to String
x = "".join(list_of_string_x)
# Printing out string after swapping characters
print("Final String is =>", x)
Output of Above Code
Final String is => uompCter
No Comments
Leave a comment Cancel