2

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.

merlin2011
  • 71,677
  • 44
  • 195
  • 329

4 Answers4

9

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.

Thijs van Dien
  • 6,516
  • 1
  • 29
  • 48
1

A slightly functional way of doing it based on itertools grouper recipe

 for x in grouper(words.split(), 4):
    print ' '.join(x)
iruvar
  • 22,736
  • 7
  • 53
  • 82
0
>>> words = '9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de'.split()
>>> [' '.join(words[i*4:i*4+4]) for i in range(len(words)/4)]
['9c 75 5a 62', '32 3b 3a fe', '40 14 46 1c', '6e d5 24 de']

or based on 1_CR's answer

from itertools import izip_longest

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)

[' '.join(x) for x in grouper(words.split(), 4)]
dansalmo
  • 11,506
  • 5
  • 58
  • 53
0
giantString= '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'

splitGiant = giantString.split(' ')
stringHolders = []
for item in xrange(len(splitGiant)/4):
    stringHolders.append(splitGiant[item*4:item*4+4])

stringHolder2 = []

for item in stringHolders:
    stringHolder2.append(' '.join(item))

print stringHolder2

the most long convoluted way to do this possible.

TehTris
  • 3,139
  • 1
  • 21
  • 33