Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is there a way to split a string of numbers into every 3rd number?

Tags:

python

list

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

123 456 789 876 567 543

like image 379
Kyle W Avatar asked May 10 '10 07:05

Kyle W


4 Answers

>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]
like image 161
Mizipzor Avatar answered Oct 17 '22 16:10

Mizipzor


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']
like image 36
miles82 Avatar answered Oct 17 '22 17:10

miles82


>>> import re
>>> a = '123456789876567543'
>>> l = re.findall('.{1,3}', a)
>>> l
['123', '456', '789', '876', '567', '543']
>>> 
like image 4
Nick Dandoulakis Avatar answered Oct 17 '22 15:10

Nick Dandoulakis


s = str(123456789876567543)
l = []
for i in xrange(0, len(s), 3):
    l.append(int(s[i:i+3]))
print l
like image 2
Tamás Avatar answered Oct 17 '22 15:10

Tamás