Most pythonic way to interleave two strings(交错两个字符串的最pythonic方法)
问题描述
将两个字符串连接在一起的最 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
在较短字符串的末尾停止迭代.在这种情况下,应该使用 而不是
(zip
zip_longestizip_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.
这篇关于交错两个字符串的最pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:交错两个字符串的最pythonic方法


- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 沿轴计算直方图 2022-01-01