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
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.