交错两个字符串的最pythonic方法

2022-01-31 00:00:00 python python-3.x python-2.7 string

问题描述

将两个字符串连接在一起的最 Pythonic 方式是什么?

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

例如:

输入:

u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'

输出:

'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'


解决方案

对我来说,最 Pythonic* 的方法是以下 几乎做同样的事情,但使用 + 用于连接每个字符串中的单个字符的运算符:

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'

它也比使用两个 join() 调用更快:

It is also faster than using two join() calls:

In [5]: l1 = 'A' * 1000000; l2 = 'a' * 1000000

In [6]: %timeit "".join("".join(item) for item in zip(l1, l2))
1 loops, best of 3: 442 ms per loop

In [7]: %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.

注意:如果两个输入字符串不同长度相同,那么较长的字符串将被截断为zip 在较短字符串的末尾停止迭代.在这种情况下,应该使用 而不是 zipzip_longest (izip_longest 在 Python 2) 中来自 itertools 模块以确保两个字符串都完全耗尽.

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 zip_longest (izip_longest in Python 2) from the itertools module to ensure that both strings are fully exhausted.

*引用 Python 之禅:可读性很重要.
Pythonic = 可读性 对我来说;i + j 只是在视觉上更容易解析,至少对我来说是这样.

*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.

相关文章