一种解决方案是使用此功能:
def chunkstring(string, length):
return (string[0+i:length+i] for i in range(0, len(string), length))
此函数使用生成器推导返回生成器。生成器返回切片的字符串,从 0 + 块长度的倍数,到块的长度 + 块长度的倍数。
您可以像列表、元组或字符串一样迭代生成器 - for i in chunkstring(s,n):
,或者将其转换为列表(例如)list(generator)
。生成器比列表更节省内存,因为它们根据需要生成元素,而不是一次生成,但是它们缺少索引等某些功能。
这个生成器最后还包含任何较小的块:
>>> list(chunkstring("abcdefghijklmnopqrstuvwxyz", 5))
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']
示例用法:
text = """This is the first line.
This is the second line.
The line below is true.
The line above is false.
A short line.
A very very very very very very very very very long line.
A self-referential line.
The last line.
"""
lines = (i.strip() for i in text.splitlines())
for line in lines:
for chunk in chunkstring(line, 16):
print(chunk)