Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string


This program is written in the Python programming language and it swaps the values of two strings "a" and "b". It does this in two steps:

  • The first step is to create two new strings "a1" and "b1" by combining the substrings of "a" and "b".
    • The new string "a1" is created by concatenating the first two characters of "b" and the last character of "a".
    • The new string "b1" is created by concatenating the first two characters of "a" and the last character of "b".
  • In the second step, the program assigns the newly created strings "a1" and "b1" back to the original variables "a" and "b".

Finally, the program prints both the original strings "a" and "b" and the swapped strings "a1" and "b1" to the console.

Source Code

a = 'abc'
b = 'xyz'
print("Before Swap :",a," ",b)
a1 = b[:2] + a[2:]
b1 = a[:2] + b[2:]
print("After Swap :",a1," ",b1)

Output

Before Swap : abc   xyz
After Swap : xyc   abz


Example Programs