是否有可能分割字符串每n个字符?

例如,假设我有一个包含以下内容的字符串:

'1234567890'

我怎样才能让它看起来像这样:

['12','34','56','78','90']

关于列表的相同问题,请参见如何将列表分割为大小相等的块?。同样的技术通常适用,尽管有一些变化。


当前回答

>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']

其他回答

我陷入了同样的困境。

这招对我很管用:

x = "1234567890"
n = 2
my_list = []
for i in range(0, len(x), n):
    my_list.append(x[i:i+n])
print(my_list)

输出:

['12', '34', '56', '78', '90']

这些答案都很好,很有用,但是语法太神秘了……为什么不写一个简单的函数呢?

def SplitEvery(string, length):
    if len(string) <= length: return [string]        
    sections = len(string) / length
    lines = []
    start = 0;
    for i in range(sections):
        line = string[start:start+length]
        lines.append(line)
        start += length
    return lines

简单地叫它:

text = '1234567890'
lines = SplitEvery(text, 2)
print(lines)

# output: ['12', '34', '56', '78', '90']

另一个使用groupby和index//n作为键来分组字母的解决方案:

from itertools import groupby

text = "abcdefghij"
n = 3

result = []
for idx, chunk in groupby(text, key=lambda x: x.index//n):
    result.append("".join(chunk))

# result = ['abc', 'def', 'ghi', 'j']

试试下面的代码:

from itertools import islice

def split_every(n, iterable):
    i = iter(iterable)
    piece = list(islice(i, n))
    while piece:
        yield piece
        piece = list(islice(i, n))

s = '1234567890'
print list(split_every(2, list(s)))

我认为这比itertools版本更短,更可读:

def split_by_n(seq, n):
    '''A generator to divide a sequence into chunks of n units.'''
    while seq:
        yield seq[:n]
        seq = seq[n:]

print(list(split_by_n('1234567890', 2)))