Split string every nth character?

Brandon L Burnett picture Brandon L Burnett · Feb 28, 2012 · Viewed 386.3k times · Source

Is it possible to split a string every nth character?

For example, suppose I have a string containing the following:

'1234567890'

How can I get it to look like this:

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

Answer

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