tags:

views:

179

answers:

4

For example, if I have a string a=123456789876567543 could i have a list like...

123 456 789 876 567 543

+2  A: 
s = str(123456789876567543)
l = []
for i in xrange(0, len(s), 3):
    l.append(int(s[i:i+3]))
print l
Tamás
Doesn't that fail if the length is not a multiple of 3?
extraneon
No, it won't, string slices simply return shorter substrings if there are not enough characters.
Tamás
I know it will fail if it isn't a multiple of 3. But for what I'm doing, it won't. Thank you very much.
Kyle W
+7  A: 
>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]
mizipzor
+4  A: 
>>> import re
>>> a = '123456789876567543'
>>> l = re.findall('.{1,3}', a)
>>> l
['123', '456', '789', '876', '567', '543']
>>> 
Nick D
+5  A: 

Recipe from the itertools docs (you can define a fillvalue when the length is not a multiple of 3):

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

s = '123456789876567543'

print [''.join(l) for l in grouper(3, s, '')]


>>> ['123', '456', '789', '876', '567', '543']
miles82