简体   繁体   English

Python:有没有办法将一串数字分成每个第三个数字?

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

For example, if I have a string a=123456789876567543 could i have a list like... 例如,如果我有一个字符串a = 123456789876567543我可以有一个像...的列表

123 456 789 876 567 543 123 456 789 876 567 543

>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]

Recipe from the itertools docs (you can define a fillvalue when the length is not a multiple of 3): 来自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

If you want right alignment: 如果你想要正确对齐:

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.

相关问题 python将每个第3个值的字符串拆分成一个嵌套格式 - python split string every 3rd value but into a nested format 获取 Python 中字符串的每第二个和第三个字符 - Get every 2nd and 3rd characters of a string in Python 有没有一种方法可以通过Python中的第n个分隔符来拆分字符串? - Is there a way to split a string by every nth separator in Python? 有没有办法在Python词典中附加第3个值? - Is there a way to attach a 3rd value in Python dictionaries? 有没有一种方法可以旋转列表中的值,但列表中的每个第3个位置都是固定的? - Is there a way to rotate values in a list but every 3rd position on the list is stationary? 有没有办法更好地编写代码来查找两个数字之间的数字? 它不是在读取第二个或第三个 elif 语句 - Is there a way to better write the code to find the number between two numbers? It's not reading the 2nd or the 3rd elif statements 有没有办法在 Python 中生成列表字符串,而无需任何其他 3rd 方包? - Is there a way to generate a list string within Python, without any other 3rd party packages? Python:将小数点后第三位拆分为float - Python: split float after 3rd decimal place 如何在python中将三阶多维数组拆分为不同的数组? - How to split 3rd order multidimensional array into different arrays in python? python每第三次迭代添加一个新的div - python add a new div every 3rd iteration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM