6

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?

The Guy with The Hat
  • 10,290
  • 8
  • 59
  • 73
Chris Headleand
  • 5,513
  • 16
  • 48
  • 66

4 Answers4

19
>>> [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().

Eric O Lebigot
  • 86,421
  • 44
  • 210
  • 254
3

How about :

>>> string = 'abcdefghijklmnopqrstuvwx'
>>> map(''.join, zip(*[iter(string)]*4))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
>>>
James
  • 14,773
  • 11
  • 43
  • 67
  • Cute but wasteful: the string is decomposed into characters that are later reassembled. Plus, this fails to pick the last characters when the string does not have a length which is a multiple of 4. – Eric O Lebigot Mar 26 '14 at 10:08
2

or:

map(lambda i: string[i:i+4], xrange(0, len(string), 4))
Eric O Lebigot
  • 86,421
  • 44
  • 210
  • 254
Elisha
  • 4,513
  • 4
  • 27
  • 45
1

Use the textwrap standard library module:

>>> import textwrap
>>> textwrap.wrap('abcdefghijklmnopq', 4)
['abcd', 'efgh', 'ijkl', 'mnop', 'q']

Edit: crap, this doesn't work right with spaces. Still leaving the answer here because the last time I had your problem, I was actually trying to wrap text, so maybe others have the same.

RemcoGerlich
  • 28,952
  • 5
  • 61
  • 78