我有这段代码,可以交错两个单词并将新的交错单词作为元组输出,但我也需要它是一个原始字符串。
from itertools import zip_longest
def interleave(word1,word2):
return ''.join(list(map(str, zip_longest(word1,word2,fillvalue=''))))
如果输入单词“cat”和“hat”,则输出
('h', 'c')('a', 'a')('t', 't').
但是我需要它来输出
hcaatt
如何将此列表格式化为普通字符串
最佳答案
使用 itertools.chain.from_iterable()
和 zip()
函数:
import itertools
w1, w2 = 'cat', 'hat'
result = ''.join(itertools.chain.from_iterable(zip(w2, w1)))
print(result)
输出:
hcaatt
关于python - 将列表格式化为字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46777086/