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
Recommended:-How to Check Python Program Execution Time
Recommended:-Python Program Find Day of Week For Given Date
Recommended:-Python Program to Print Sum of All Array Elements
Recommended:-Python Program to Find the GCD of Two Numbers
Recommended:-Python Program to Find the LCM of the Array Elements
Recommended:-Python Code to Draw a Pie Chart
Recommended:-Python Program to Display the Current Date and Time
Recommended:-Python Program to Find Area of Triangle
Recommended:-Python Program to Find the Area of Rectangle
Recommended:-Python Program to Print All Timezones
Recommended:-Python Count the Occurrences in an Array
Recommended:-Python Program to Print Binary Numbers From 1 to N