Python | Swapping Characters in a String

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

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts