Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into a list, with items of equal length [duplicate]

I have a string (without spaces) which I need to split into a list with items of equal length. I'm aware of the split() method, but as far as I'm aware this only splits via spaces and not via length.

What I want to do is something like this:

string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)

>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]

I have thought about looping through the list but I was wondering if there was a simpler solution?

like image 558
Chris Headleand Avatar asked Mar 26 '14 09:03

Chris Headleand


3 Answers

>>> [string[start:start+4] for start in range(0, len(string), 4)]
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']

It works even if the last piece has less than 4 characters.

PS: in Python 2, xrange() should be used instead of range().

like image 182
Eric O Lebigot Avatar answered Oct 24 '22 09:10

Eric O Lebigot


How about :

>>> string = 'abcdefghijklmnopqrstuvwx'
>>> map(''.join, zip(*[iter(string)]*4))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
>>>
like image 3
James Avatar answered Oct 24 '22 09:10

James


or:

map(lambda i: string[i:i+4], xrange(0, len(string), 4))
like image 2
Elisha Avatar answered Oct 24 '22 09:10

Elisha