gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:31:30 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com