2010-03-01 10 views

Répondre

3

Peut-être quelque chose comme ça?

>>> a = "123456789" 
>>> for grp in [a[:3], a[3:6], a[6:]]: 
    print grp 

Bien sûr, si vous avez besoin de généraliser,

>>> def split3(aString): 
     while len(aString) > 0: 
       yield aString[:3] 
       aString = aString[3:] 


>>> for c in split3(a): 
     print c 
+0

+1 Wouldn » t 'alors que aString' est meilleur que' while len (aString)> 0'? –

+0

Peut-être :-) Je préfère les booléens plus clairs, mais c'est une question de goût personnel. –

2
>>> s = "123456789" 
>>> import textwrap 
>>> textwrap.wrap(s,3) 
['123', '456', '789'] 

ou vous pouvez utiliser itertools

import itertools 
def grouper(n, iterable): 
    args = [iter(iterable)] * n 
    return itertools.izip_longest(*args) 

for i in grouper(3,"o my gosh"): 
    print i 

sortie

$ ./python.py 
('o', ' ', 'm') 
('y', ' ', 'g') 
('o', 's', 'h') 
+1

-1: Cela ne se comportera pas comme prévu pour toutes les chaînes: textwrap.wrap ("je suis sam!", 3) = ['i', 'suis', 'sam', '!'] – truppo

Questions connexes