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.
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:
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:
Same program on python shell:
Program Video with Compile and Run
You may also like to learn or practice the same program in other popular programming languages: