Most pythonic way to interleave two strings

前端 未结 14 1134
暗喜
暗喜 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:12

    Feels a bit un-pythonic not to consider the double-list-comprehension answer here, to handle n string with O(1) effort:

    "".join(c for cs in itertools.zip_longest(*all_strings) for c in cs)
    

    where all_strings is a list of the strings you want to interleave. In your case, all_strings = [u, l]. A full use example would look like this:

    import itertools
    a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    b = 'abcdefghijklmnopqrstuvwxyz'
    all_strings = [a,b]
    interleaved = "".join(c for cs in itertools.zip_longest(*all_strings) for c in cs)
    print(interleaved)
    # 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
    

    Like many answers, fastest? Probably not, but simple and flexible. Also, without too much added complexity, this is slightly faster than the accepted answer (in general, string addition is a bit slow in python):

    In [7]: l1 = 'A' * 1000000; l2 = 'a' * 1000000;
    
    In [8]: %timeit "".join(a + b for i, j in zip(l1, l2))
    1 loops, best of 3: 227 ms per loop
    
    In [9]: %timeit "".join(c for cs in zip(*(l1, l2)) for c in cs)
    1 loops, best of 3: 198 ms per loop
    

提交回复
热议问题