0

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

dorothy
  • 1,213
  • 5
  • 20
  • 35
  • 1
    Also, 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
  • 1
    See [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 Answers3

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
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