[ACCEPTED]-How do I slice a string every 3 indices?-slice

Accepted answer
Score: 20

In short, you can't.

In longer, you'll need 2 to write your own function, possibly:

def split(str, num):
    return [ str[start:start+num] for start in range(0, len(str), num) ]

For 1 example:

>>> split("xxxXXX", 3)
['xxx', 'XXX']
>>> split("xxxXXXxx", 3)
['xxx', 'XXX', 'xx']
Score: 7

one difference between splitting lists into 8 chunks of 3 and strings into chunks of 3 7 is that the re module works with strings 6 rather than lists.

If performance is important 5 (ie you are splitting thousands of strings), you 4 should test how the various answers compare 3 in your application

>>> import re
>>> re.findall('...','XXXxxxXXXxxxXXXxxxXXXxxxXXX')
['XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX']

>>> chunksize=3
>>> re.findall('.{%s}'%chunksize,'XXXxxxXXXxxxXXXxxxXXXxxxXXX')
['XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX']

This works because . means 2 "match any character" in regular expressions.
.{3} means 1 "match any 3 characters", and so on

Score: 4

As far as I know there is no built in method 2 that allows you to chunk an str every x 1 indices. However this should works:

 str = "stringStringStringString"

 def chunk_str(str, chunk_size):
   return [str[i:i+chunk_size] for i in range(0, len(str), chunk_size)]

 chunk_str(str,3)

produces:

['str', 'ing', 'Str', 'ing', 'Str', 'ing', 'Str', 'ing']
Score: 1

Copying an answer from How do you split a list into evenly sized chunks in Python? since Nov 2008:

Directly 5 from the Python documentation (recipes for 4 itertools):

from itertools import izip, chain, repeat

def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

An alternate take, as suggested 3 by J.F.Sebastian:

from itertools import izip_longest

def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

I guess Guido's time machine 2 works—worked—will work—will have worked—was 1 working again.

More Related questions