Pythonic way to split a line into groups of four words?
Question: Suppose I have string that look like the following, of varying length, but
with the number of "words" always equal to multiple of 4.

    
    
    9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de
    c6 11 17 cc 3d d7 99 f4 a1 3f 7f 4c
    

I would like to chop them into strings like `9c 75 5a 62` and `32 3b 3a fe`

I could use a regex to match the exact format, but I wonder if there is a more
straightforward way to do it, because regex seems like overkill for what
should be a simple problem.


Answer: A staight-forward way of doing this is as follows:

    
    
    wordlist = words.split()
    for i in xrange(0, len(wordlist), 4):
        print ' '.join(wordlist[i:i+4])
    

If for some reason you can't make a list of all words (e.g. an infinite
stream), you could do this:

    
    
    from itertools import groupby, izip
    words = (''.join(g) for k, g in groupby(words, ' '.__ne__) if k)
    for g in izip(*[iter(words)] * 4):
        print ' '.join(g)
    

Disclaimer: I didn't come up with this pattern; I found it in a similar topic
a while back. It arguably relies on an implementation detail, but it would be
quite a bit more ugly when done in a different way.

