This question already has an answer here:
I'm using Python to program for the lab I work at. How can I slice out every 3 characters in a given string and append it to a list?
i.e. XXXxxxXXXxxxXXXxxxXXXxxxXXX (where X or x is any given letter)
string = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'
mylist = []
for x in string:
string[?:?:?]
mylist.append(string)
I want the list to look like this: ['XXX','xxx','XXX','xxx','XXX'....etc]
Any ideas?
Copying an answer from How do you split a list into evenly sized chunks in Python? since Nov 2008:
Directly from the Python documentation (recipes for itertools):
An alternate take, as suggested by J.F.Sebastian:
I guess Guido's time machine works—worked—will work—will have worked—was working again.
one difference between splitting lists into chunks of 3 and strings into chunks of 3 is that the re module works with strings rather than lists.
If performance is important (ie you are splitting thousands of strings), you should test how the various answers compare in your application
This works because
.
means "match any character" in regular expressions..{3}
means "match any 3 characters", and so onAs far as I know there is no built in method that allows you to chunk an str every x indices. However this should works:
produces:
In short, you can't.
In longer, you'll need to write your own function, possibly:
For example: