Swap First Two Characters in Each String in Python

To swap first two characters in a string python; Through this tutorial, i am going to show you how to swap first two characters of each string in python.

Python Program to Swap First Two Character of Each String

  • Python Program to Swap First Two Character of Each String using Replace()
  • Python Program to Swap First Two Character of Each String using str

Python Program to Swap First Two Character of Each String using Replace()

  • Get input strings one by one from user in program
  • Swap string using slicing , replace() method and store result in variables.
  • Print swapped two characters of string
#take strings from user
str1 = input("Please Enter First String : ")
str2 =input("Please Enter Second String : ")
x=str1[0:2]
str1=str1.replace(str1[0:2],str2[0:2])
str2=str2.replace(str2[0:2],x)
print("Your first string has become :- ",str1)
print("Your second string has become :- ",str2)

After executing the program, the output will be:

Please Enter First String :  sam
Please Enter Second String :  mak

Your first has become :-  mam
Your second has become :-  sak

Python Program to Swap First Two Character of Each String using str

  • Allow user to input strings one by one, which user want to swap first two characters.
  • Swap string using slicing and store result in variables.
  • Print results.
#take input string from user
str1 = input("Please Enter First String : ")
str2 =input("Please Enter Second String : ")
#swap first two characters of given string
x = str2[:2] + str1[2:]
y = str1[:2] + str2[2:]
#print result
print("Your first has become :- ",x)
print("Your second has become :- ",y)

After executing the program, the output will be:

Please Enter First String :  sam
Please Enter Second String :  mack
Your first has become :-  mam
Your second has become :-  sack

Recommended Python Tutorials

Be First to Comment

Leave a Reply

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