Most pythonic way to interleave two strings
What's the most pythonic way to mesh two strings together?
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' l = 'abcdefghijklmnopqrstuvwxyz'
For me, the most pythonic* way is the following which pretty much does the same thing but uses the
+ operator for concatenating the individual characters in each string:
res = "".join(i + j for i, j in zip(u, l)) print(res) # 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
It is also faster than using two
In : l1 = 'A' * 1000000; l2 = 'a' * 1000000 In : %timeit "".join("".join(item) for item in zip(l1, l2)) 1 loops, best of 3: 442 ms per loop In : %timeit "".join(i + j for i, j in zip(l1, l2)) 1 loops, best of 3: 360 ms per loop
Faster approaches exist, but they often obfuscate the code.
Note: If the two input strings are not the same length then the longer one will be truncated as
zip stops iterating at the end of the shorter string. In this case instead of
zip one should use
izip_longest in Python 2) from the
itertools module to ensure that both strings are fully exhausted.
*To take a quote from the Zen of Python : Readability counts.
Pythonic = readability for me;
i + j is just visually parsed more easily, at least for my eyes.
★ Back to homepage or read more recommendations: