将字符串拆分为 2 个字母的段
问题描述
我有一个字符串,我需要将它分成 2 个字母的部分.例如,'ABCDXY'
应该变成 ['AB', 'CD', 'XY']
.奇数字符情况下的行为可能完全是任意的(我会提前检查长度).
I have a string, which I need to split into 2-letter pieces. For example, 'ABCDXY'
should become ['AB', 'CD', 'XY']
. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance).
有没有什么办法可以避免丑陋的循环?
Is there any way to do this without an ugly loop?
解决方案
>>> [s[i:i + 2] for i in range(0, len(s), 2)]
['AB', 'CD', 'XY']
相关文章