首页 > 解决方案 > 如何按索引添加两个字符串

问题描述

我尝试了很多次,但做不到。

这是一个例子:

print( concat_corresponding( "12345", "6789XYZ" ) )

期望的输出:

162738495XYZ

标签: pythonstringfunctionsliceindices

解决方案


这是一种方法itertools

from itertools import chain, zip_longest

a = "12345"
b = "6789XYZ"

res = ''.join(list(chain.from_iterable(zip_longest(a, b, fillvalue=''))))

# '162738495XYZ'

请注意,列表转换不是必需的,但可以提高性能


推荐阅读