Most pythonic way to interleave two strings

前端 未结 14 1110
暗喜
暗喜 2020-11-27 14:34

What\'s the most pythonic way to mesh two strings together?

For example:

Input:

u = \'ABCDEFGHIJKLMNOPQRSTUVWXYZ\'
l = \'abcdefghijklmnopqrst         


        
14条回答
  •  暖寄归人
    2020-11-27 15:20

    A lot of these suggestions assume the strings are of equal length. Maybe that covers all reasonable use cases, but at least to me it seems that you might want to accomodate strings of differing lengths too. Or am I the only one thinking the mesh should work a bit like this:

    u = "foobar"
    l = "baz"
    mesh(u,l) = "fboaozbar"
    

    One way to do this would be the following:

    def mesh(a,b):
        minlen = min(len(a),len(b))
        return "".join(["".join(x+y for x,y in zip(a,b)),a[minlen:],b[minlen:]])
    

提交回复
热议问题