Python | Swapping Two Strings

If you’ve string variables let’s say x, y having values as “Computer” and “Science” respectively.
x = “Computer”
y = “Science”

Now you want to swap x string with y string. Means now you want x to be “Science” and y to be “Computer”. This process of exchanging values of string variables is called swapping.
In this article, I’ll discuss How to Swap two strings in Python Programming Language?

Steps for Swapping Two Strings in Python

  1. Define Two string variables first_string, second_string
  2. Define a Temporary Variable(temp) being equal to first_string
  3. Assign first_string variable value of second_string using first_string = second_string statement
  4. Assigning temp variable value to second_string variable using second_string = temp statement

That’s it first_string value has been swapped with second_string.

Python Code for Swapping Two Strings

# Python Code for Swapping Two Strings

first_string = "Hello"
second_string = "How are you?"

# Printing out each string before swapping
print("First string before swapping is =>", first_string)
print("Second string before swapping is =>", second_string)

# Swapping first_string with second_string
# Declaring a temporary variable(temp) for Swapping
temp = first_string
first_string = second_string
second_string = temp

# Printing out each string after swapping
print("First string after swapping is =>", first_string)
print("Second string after swapping is =>", second_string)

Output of Above Code

First string before swapping is => Hello
Second string before swapping is => How are you?

First string after swapping is => How are you?
Second string after swapping is => Hello


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

Leave a Reply

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

Recent Posts