每隔N个字符拆分字符串?

2024-04-23 14:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

每N个字符可以分割一个字符串吗?

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

'1234567890'

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

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

Tags: 字符串个字符
3条回答

为了完整起见,您可以使用regex执行此操作:

>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']

对于奇数个字符,可以执行以下操作:

>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']

您还可以执行以下操作,以将regex简化为更长的块:

>>> import re
>>> re.findall('.{1,2}', '123456789')
['12', '34', '56', '78', '9']

如果字符串很长,可以使用re.finditer逐块生成。

在python中已经有一个内置函数用于此目的。

>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']

这就是wrap的docstring所说的:

>>> 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.
'''
>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']

相关问题 更多 >