[英]Python: Is there a way to split a string of numbers into every 3rd number?
例如,如果我有一個字符串a = 123456789876567543我可以有一個像...的列表
123 456 789 876 567 543
>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]
來自itertools文檔的配方(當長度不是3的倍數時,您可以定義fillvalue):
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']
>>> import re
>>> a = '123456789876567543'
>>> l = re.findall('.{1,3}', a)
>>> l
['123', '456', '789', '876', '567', '543']
>>>
s = str(123456789876567543)
l = []
for i in xrange(0, len(s), 3):
l.append(int(s[i:i+3]))
print l
如果你想要正確對齊:
a='123456789876567543'
format(int(a),',').split(',')
['123', '456', '789', '876', '567', '543']
a='12345'
format(int(a),',').split(',')
['12', '345']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.