在循环中将字符串分组为3个(python)
我有一个九个字符的字符串,想要在一个循环中对每组三个字符进行操作。
我该如何在Python中实现这个呢?
3 个回答
4
>>> s = "123456789"
>>> import textwrap
>>> textwrap.wrap(s,3)
['123', '456', '789']
import itertools
def grouper(n, iterable):
args = [iter(iterable)] * n
return itertools.izip_longest(*args)
for i in grouper(3,"o my gosh"):
print i
$ ./python.py
('o', ' ', 'm')
('y', ' ', 'g')
('o', 's', 'h')
或者你可以使用itertools这个工具
输出结果
4
也许可以像这样做?
>>> a = "123456789"
>>> for grp in [a[:3], a[3:6], a[6:]]:
print grp
当然,如果你需要更通用的写法,
>>> def split3(aString):
while len(aString) > 0:
yield aString[:3]
aString = aString[3:]
>>> for c in split3(a):
print c
3
最简单的方法:
>>> s = "123456789"
>>> for group in (s[:3], s[3:6], s[6:]): print group
...
123
456
789
在更一般的情况下,可以参考这个链接:http://code.activestate.com/recipes/303799-chunks/