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
- Define Two string variables first_string, second_string
- Define a Temporary Variable(temp) being equal to first_string
- Assign first_string variable value of second_string using first_string = second_string statement
- 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)
print("\n")
# 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
No Comments
Leave a comment Cancel