Split string into strings by length?

后端 未结 15 2179
半阙折子戏
半阙折子戏 2020-11-27 06:31

Is there a way to take a string that is 4*x characters long, and cut it into 4 strings, each x characters long, without knowing the length of the s

15条回答
  •  旧时难觅i
    2020-11-27 06:52

    Here is a one-liner that doesn't need to know the length of the string beforehand:

    from functools import partial
    from StringIO import StringIO
    
    [l for l in iter(partial(StringIO(data).read, 4), '')]
    

    If you have a file or socket, then you don't need the StringIO wrapper:

    [l for l in iter(partial(file_like_object.read, 4), '')]
    

提交回复
热议问题