codescracker


python

Python Program to Swap Two Strings



« Previous Program Next Program »


Swap Two Strings in Python

To swap two strings in python, first ask from user to enter value of both the string. After entering value of the two strings, just swap the two string using the third variable. After swapping the two strings, print the result as output.

Python Programming Code to Swap Two Strings

Following python program ask from user to enter the value of two strings to swap both the string, and then print the result as output:

# Python Program - Swap Two Strings

print("Enter 'x' for exit.");
string1 = input("Enter First String to swap: ");
if string1 == 'x':
    exit();
else:
    string2 = input("Enter Second String to swap: ");
    print("\nBoth String before swap:");
    print("First String =",string1);
    print("Second String =",string2);
    temp = string1;
    string1 = string2;
    string2 = temp;
    print("\nBoth String after swap:");
    print("First String =", string1);
    print("Second String =", string2);

Here is the sample run of the above python program to illustrate how to swap two strings in python:

swap two string python

Now enter the first string say codes, press enter and enter again the second string say cracker, again press enter key to swap the given two string as shown here:

swapping of two string python

Same program on python shell:

python swap two strings

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test