python - 将两个字符串的字符相加

标签 python python-3.x

def merge(string1, string2):        
    print( "".join(i for j in zip(string1, string2) for i in j))

当我运行 merge("big","small") 时,输出为 bsimga,我希望代码输出 bsimgall

即使字符串长度不同,如何以交替方式添加两个字符串中的字符?

最佳答案

zip() 只会生成对,直到最短迭代被耗尽。使用itertool.zip_longest()继续迭代并使用填充值来填充较短的字符串。使用空字符串来填充:

from itertools import zip_longest

def merge(string1, string2):        
    print("".join(i for j in zip_longest(string1, string2, fillvalue='') for i in j))

您可以将连接留给print():

def merge(string1, string2):        
    print(*(i for j in zip_longest(string1, string2, fillvalue='') for i in j), sep='')

您可以使用itertools.chain.from_iterable()压平结果:

from itertools import chain, zip_longest

def merge(string1, string2):        
    print(*chain.from_iterable(zip_longest(string1, string2, fillvalue='')), sep='')

关于python - 将两个字符串的字符相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46772609/

相关文章:

python - 读取外部 Excel 文件后,我的 Pandas 数据框列中的值不准确

python-3.x - BigQuery 更新如何获取更新的行数

python - 理解为什么这个 python 代码随机工作

Python ImportError 无法导入名称

python - 如何将分钟添加到 datetime.time。 python / Pandas

python - 使用 Tkinter 不显示窗口

python - 使用不正确的 python 版本从 .deb 文件安装程序

Python - 如果元素尚未包含在列表中,如何追加到列表中?

python - 训练神经网络后,我为每个输入数据获得相同的输出(2000 个输入,1 个输出)

python - 将 URL 的标题部分拆分为单独的列 - Python