Split string into even chunks

How can I take a string like 'aaaaaaaaaaaaaaaaaaaaaaa' and divide it into 4 tuples long, e.g. ( aaaa , aaaa , aaaa )

+13
python string tuples
source share
6 answers

Use textwrap.wrap :

 >>> import textwrap >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa' >>> textwrap.wrap(s, 4) ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa'] 
+20
source share

Using a list comprehension, a generator expression:

 >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa' >>> [s[i:i+4] for i in range(0, len(s), 4)] ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa'] >>> tuple(s[i:i+4] for i in range(0, len(s), 4)) ('aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa') >>> s = 'a bcdefghi j' >>> tuple(s[i:i+4] for i in range(0, len(s), 4)) ('a bc', 'defg', 'hi j') 
+12
source share

Another solution using regex:

 >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa' >>> import re >>> re.findall('[az]{4}', s) ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa'] >>> 
+3
source share

You can use the recipe grouper , zip(*[iter(s)]*4) :

 In [113]: s = 'aaaaaaaaaaaaaaaaaaaaaaa' In [114]: [''.join(item) for item in zip(*[iter(s)]*4)] Out[114]: ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa'] 

Note that textwrap.wrap cannot split s into lines of length 4 if the line contains spaces:

 In [43]: textwrap.wrap('I am a hat', 4) Out[43]: ['I am', 'a', 'hat'] 

The grouper recipe is faster than using textwrap :

 In [115]: import textwrap In [116]: %timeit [''.join(item) for item in zip(*[iter(s)]*4)] 100000 loops, best of 3: 2.41 ยตs per loop In [117]: %timeit textwrap.wrap(s, 4) 10000 loops, best of 3: 32.5 ยตs per loop 

And the grouper recipe can work with any iterator, and textwrap only works with strings.

+2
source share
 s = 'abcdef' 

We need to break in parts 2

 [s[pos:pos+2] for pos,i in enumerate(list(s)) if pos%2 == 0] 

Answer:

 ['ab', 'cd', 'ef'] 
0
source share
 s = 'abcdefghi' 

k - no parts of the string

 k = 3 

parts - list to store parts of the string

 parts = [s[i:i+k] for i in range(0, len(s), k)] 

parts โ†’ ['abc', 'def', 'ghi']

0
source share

All Articles