definterleave(s1, s2):
i = j =0
res =[]while i <len(s1)and j <len(s2):
res.append(s1[i])
res.append(s2[j])
i +=1
j +=1return''.join(res +[s1[i:], s2[j:]])# 拼接剩余部分
str1="abc"
str2="123"print(interleave(str1, str2))
优点:代码可读性强,适合教学场景。
2、zip_longest魔法(极简方案)
利用itertools.zip_longest自动填充缺失值,过滤无效字符:
from itertools
import zip_longest
definterleave(s1, s2):return''.join([c for pair in zip_longest(s1, s2)for c in pair if c isnotNone])
str1="abc"
str2="123"print(interleave(str1, str2))
definterleave(*strings):
max_len =max(len(s)for s in strings)return''.join([s[i]for i inrange(max_len)for s in strings if i <len(s)])
str1="abc"
str2="123"
str3="xyz"print(interleave(str1, str2, str3))