在Python中,当两个字符串的长度不相等时,如何交织它们?

2024-06-28 18:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道一种使用Python交错两个字符串的方法,但只有当它们的长度相等时才有效:

u = 'Abcd'
l = 'Wxyz'
res = "".join(i + j for i, j in zip(u, l))
print(res)

这将给出正确的输出:AWbxcydz 但是如果字符串是u = 'Utkarsh'l = 'Jain',那么同一个方法不能给出正确的答案。有人能给我一个建议吗?在


Tags: 方法字符串答案inforreszip建议
1条回答
网友
1楼 · 发布于 2024-06-28 18:45:16

itertools使用zip_longest。在

from itertools import zip_longest

u = 'Abcdefgh'
l = 'Wxyz'
res = "".join(i + j for i, j in zip_longest(u, l, fillvalue=''))
print(res)

相关问题 更多 >