How can I split a string on 2's, eg "string" would be split into groups of "st", "ri","ng". I check the doc, groupby from itertools seems to be what i need. However, is there a way to do it simply by not using itertools? thanks
Asked
Active
Viewed 309 times
0
-
1Also, http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks?lq=1 – Ilmo Euro Sep 09 '13 at 04:33
-
1See [this answer](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434328#434328) for a non-itertools version. – Burhan Khalid Sep 09 '13 at 05:13
-
This is the actual answer: http://stackoverflow.com/questions/12328108/how-can-i-split-a-string-in-python – Henrik Andersson Sep 09 '13 at 06:10
3 Answers
2
You could do it without itertools, but it will be slower. Unless it's a learning excersize, use the "grouper" recipe from the itertools page:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)

theodox
- 12,028
- 3
- 23
- 36
-
1
-
I prefer [@nosklo's answer](http://stackoverflow.com/a/434328/790387) from the linked question since it doesn't have version restrictions – Burhan Khalid Sep 09 '13 at 05:12
-
Depending on Python 2.6, released in 2008, is hardly a serious version restriction. – user4815162342 Sep 09 '13 at 06:12
-
thanks. i guess if I compile my script to executable, it might not have version restrictions? – dorothy Sep 09 '13 at 07:26
-
@dorothy if you use `py2exe` or `freeze`, the version you're using is bundled with the program, so you don't have to worry about versions. – Ilmo Euro Sep 09 '13 at 07:44
1
s='your input string'
ans=[ ]
i=0
while i < len(s):
ans.append( s[ i:i+2 ] )
i+=2
print ans

Henrik Andersson
- 45,354
- 16
- 98
- 92

ayush1794
- 101
- 1
- 7
0
If you just want to do the two character groups without itertools, you can use this:
s = 'string'
groups = [''.join(g) for g in zip(s[:-1:2], s[1::2])]
Note that this only works properly for even-length strings.

chthonicdaemon
- 19,180
- 2
- 52
- 66