# Program to merge strings alternately using Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t. We have to merge them by adding letters in alternating fashion, starting from s. If s and t are not of same length, add the extra letters onto the end of the merged string.

So, if the input is like s = "major" t = "general", then the output will be "mgaejnoerral", as t is larger than s, so we have added extra part "ral" at the end.

To solve this, we will follow these steps −

• i := j := 0

• result := blank string

• while i < size of s and j < size of t, do

• result := result concatenate s[i] concatenate t[j]

• i := i + 1

• j := j + 1

• while i < size of s, do

• result := result concatenate s[i]

• i := i + 1

• while j < size of t , do

• result := result concatenate t[j]

• j := j + 1

• return result

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(s, t):
i = j = 0
result = ""
while i < len(s) and j < len(t):
result += s[i] + t[j]
i+=1
j+=1
while i < len(s):
result += s[i]
i += 1
while j < len(t):
result += t[j]
j += 1
return result
s = "major"
t = "general"
print(solve(s, t))

## Input

"major", "general"

## Output

mgaejnoerral
Published on 27-May-2021 14:22:47