如何将字符串分成五个块?

flo*_*ocd 1 python string chunking

所以程序会读取一个带字符串的文件.然后该字符串将保存到另一个文件中,但该字符串将被拆分为5个组.

例.

鉴于其内容file1.txt将是thecatsatonthemat,内容file2.txt将是theca tsato nthem at.

Gor*_*bot 6

这是一个枚举器,它将为您提供5个字符块:

def chunk(l):
    for i in range(0, len(l), 5):
        yield l[i:i+5]
Run Code Online (Sandbox Code Playgroud)

使用它像:

>>> l = 'abcdefghijqlmnopqrstuvwxyz'
>>> for sub in chunk(l):
>>>     print(sub)

abcde
fghij
klmno
pqrst
uvwxy
z
Run Code Online (Sandbox Code Playgroud)

  • Grats,您的答案如下(:https://github.com/drathier/stack-overflow-import (7认同)