1

I have this code that interleaves two words and outputs the new interleaved word as a tuple, but I need it too be a raw string.

from itertools import zip_longest
def interleave(word1,word2):
    return ''.join(list(map(str, zip_longest(word1,word2,fillvalue=''))))

If inputting the words, cat and hat, this outputs

('h', 'c')('a', 'a')('t', 't'). 

But I need it to output

hcaatt

How could I go about formatting this list into a normal string

  • see [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – cowbert Oct 16 '17 at 18:51

2 Answers2

2

With itertools.chain.from_iterable() and zip() functions:

import itertools

w1, w2 = 'cat', 'hat'
result = ''.join(itertools.chain.from_iterable(zip(w2, w1)))

print(result)

The output:

hcaatt
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

you could use reduce to reach your goal:

word1, word2 = 'cat', 'hat'
result = ''.join(reduce(lambda x, y: x+y, zip(word1, word2)))
print(result)
rachid el kedmiri
  • 2,376
  • 2
  • 18
  • 40