将字符串分成特定长度的组 [英] Splitting string into groups of specific length

查看:108
本文介绍了将字符串分成特定长度的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将诸如"abcdefghijklmnopqrstuvwxyz"这样的字符串分成2组的列表(将字符串分为:["ab", "bc", "cd", ... "yz])的最佳方法是在Python中吗.

I was wondering what the best way to split up a string such as "abcdefghijklmnopqrstuvwxyz" into a list of groups of 2 (splitting the string into: ["ab", "bc", "cd", ... "yz]) is in Python.

或者以3组为一组:将字符串拆分为["abc", "bcd", "cde", ... "xyz"]

Or what about in groups of 3: splitting the string into ["abc", "bcd", "cde", ... "xyz"]

谢谢!

推荐答案

这是适用于所有可迭代对象的

Here is one that works for any iterable

>>> from itertools import tee, izip, islice
>>> chunksize = 2
>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> t = tee(s, chunksize)
>>> for i, j in enumerate(t):
...  next(islice(j, i, i), None)
...
>>> ["".join(k) for k in izip(*t)]
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl', 'lm', 'mn', 'no', 'op', 'pq', 'qr', 'rs', 'st', 'tu', 'uv', 'vw', 'wx', 'xy', 'yz']

如果s始终是str,则更简单

>>> [s[i: i + chunksize] for i in range(len(s) + 1 - chunksize)]
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl', 'lm', 'mn', 'no', 'op', 'pq', 'qr', 'rs', 'st', 'tu', 'uv', 'vw', 'wx', 'xy', 'yz']

这篇关于将字符串分成特定长度的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆