Program to merge two strings in alternating fashion in Python

Suppose we have two strings s and t of same size. We have to join letters from s and t in alternative fashion. So take s[i] concatenate with t[i] then go for next letter and so on.

So, if the input is like s = "hello" t = "world", then the output will be "hweolrllod"

To solve this, we will follow these steps −

  • zipped := perform zip operation on s and t to make pairs like (s[i], t[i])
  • zipped := make a list where each element is s[i] concatenate t[i]
  • return the zipped list by joining them into a single string.


Let us see the following implementation to get better understanding −

def solve(s, t):
   zipped = list(zip(s, t))
   zipped = map(lambda x: x[0]+x[1], zipped)
   return ''.join(zipped)

s = "hello"
t = "world"
print(solve(s, t))


"hello", "world"