Pythonic将一条线分成四个单词组的方式?

mer*_*011 2 python string

假设我的字符串看起来如下,长度不一,但"字"的数量总是等于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
Run Code Online (Sandbox Code Playgroud)

我想,切成像串 9c 75 5a 6232 3b 3a fe

我可以使用正则表达式来匹配确切的格式,但我想知道是否有更直接的方法来做到这一点,因为正则表达式看起来像是一个简单的问题.

Thi*_*ien 9

一种直截了当的做法如下:

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

如果由于某种原因你无法列出所有单词(例如无限流),你可以这样做:

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)
Run Code Online (Sandbox Code Playgroud)

免责声明:我没有提出这种模式; 我在一段时间内发现了类似的话题.它可以说依赖于一个实现细节,但是当以不同的方式完成时会更加丑陋.