2

次のようなさまざまな長さの文字列があるとしますが、「単語」の数は常に 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

私はそれらを次のような文字列に切り刻みたいと思い 9c 75 5a 62ます32 3b 3a fe

正規表現を使用して正確な形式に一致させることもできますが、単純な問題であるべきことに対して正規表現はやり過ぎのように思われるため、もっと簡単な方法があるのではないかと思います。

4

4 に答える 4

1

itertools grouper レシピに基づいた少し機能的な方法

 for x in grouper(words.split(), 4):
    print ' '.join(x)
于 2013-06-06T18:39:33.197 に答える
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

これを可能にするための最も複雑な方法です。

于 2013-06-06T18:43:23.123 に答える
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']

または1_CRの回答に基づく

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)]
于 2013-06-06T18:41:31.283 に答える