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,836
  • 8
  • 57
  • 75
Chris Headleand
  • 6,003
  • 16
  • 51
  • 69

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
  • 91,433
  • 48
  • 218
  • 260
3

How about :

>>> string = 'abcdefghijklmnopqrstuvwx'
>>> map(''.join, zip(*[iter(string)]*4))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
>>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73
  • 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
  • 91,433
  • 48
  • 218
  • 260
Elisha
  • 4,811
  • 4
  • 30
  • 46
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
  • 30,470
  • 6
  • 61
  • 79