Merge two strings by taking characters alternatively from each string
Sample string 1 : PYTHON
Sample string 2 : python
Output: PpYyTtHhOoNn
Let us understand the two scenarios of this problem
Scenario1: If both the strings are of same length:
string1=input("Enter first string: ") string2=input("Enter second string: ") i,j=0,0 # object initialization using Tuple Unpacking result="" while i<len(string1) or j<len(string2): result=result+string1[i]+string2[j] i=i+1 j=j+1 print("You entered first string : ",string1) print("You entered second string : ",string2) print("Final result after alternate merge: \n", result )
Scenario 2: If the strings have different length:
string1=input("Enter first string: ") string2=input("Enter second string: ") i,j=0,0 # object initialization using Tuple Unpacking result="" while i<len(string1) or j<len(string2): if i<len(string1): result=result+string1[i] i=i+1 if j<len(string2): result=result+string2[j] j=j+1 print("You entered first string: ",string1) print("You entered second string: ",string2) print("Final result after alternate merge: \n", result )
No comments:
Post a Comment