是否有可能分割字符串每n个字符?
例如,假设我有一个包含以下内容的字符串:
'1234567890'
我怎样才能让它看起来像这样:
['12','34','56','78','90']
关于列表的相同问题,请参见如何将列表分割为大小相等的块?。同样的技术通常适用,尽管有一些变化。
是否有可能分割字符串每n个字符?
例如,假设我有一个包含以下内容的字符串:
'1234567890'
我怎样才能让它看起来像这样:
['12','34','56','78','90']
关于列表的相同问题,请参见如何将列表分割为大小相等的块?。同样的技术通常适用,尽管有一些变化。
当前回答
短字符串的简单递归解决方案:
def split(s, n):
if len(s) < n:
return []
else:
return [s[:n]] + split(s[n:], n)
print(split('1234567890', 2))
或以这样的形式:
def split(s, n):
if len(s) < n:
return []
elif len(s) == n:
return [s]
else:
return split(s[:n], n) + split(s[n:], n)
,它更明确地说明了递归方法中的典型分治模式(尽管实际上没有必要这样做)。
其他回答
试试这个:
s='1234567890'
print([s[idx:idx+2] for idx,val in enumerate(s) if idx%2 == 0])
输出:
['12', '34', '56', '78', '90']
python中已经有一个内置的函数。
>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']
这是wrap的文档字符串说的:
>>> help(wrap)
'''
Help on function wrap in module textwrap:
wrap(text, width=70, **kwargs)
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
'''
短字符串的简单递归解决方案:
def split(s, n):
if len(s) < n:
return []
else:
return [s[:n]] + split(s[n:], n)
print(split('1234567890', 2))
或以这样的形式:
def split(s, n):
if len(s) < n:
return []
elif len(s) == n:
return [s]
else:
return split(s[:n], n) + split(s[n:], n)
,它更明确地说明了递归方法中的典型分治模式(尽管实际上没有必要这样做)。
使用groupby的解决方案:
from itertools import groupby, chain, repeat, cycle
text = "wwworldggggreattecchemggpwwwzaz"
n = 3
c = cycle(chain(repeat(0, n), repeat(1, n)))
res = ["".join(g) for _, g in groupby(text, lambda x: next(c))]
print(res)
输出:
['www', 'orl', 'dgg', 'ggr', 'eat', 'tec', 'che', 'mgg', 'pww', 'wza', 'z']
我陷入了同样的困境。
这招对我很管用:
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']