Split string every nth character? Split string every nth character? python python

Split string every nth character?


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


Just to be complete, you can do this with a regex:

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

For odd number of chars you can do this:

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

You can also do the following, to simplify the regex for longer chunks:

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

And you can use re.finditer if the string is long to generate chunk by chunk.


There is already an inbuilt function in python for this.

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

This is what the docstring for wrap says:

>>> 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.'''