Split string into strings by length?

后端 未结 15 2177
半阙折子戏
半阙折子戏 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条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 07:15

    And for dudes who prefer it to be a bit more readable:

    def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0
        size = len(string)
        chunksize = size//x
        for pos in range(0, size, chunksize):
            yield string[pos:pos+chunksize]
    

    output:

    >>> list(itersplit_into_x_chunks('qwertyui',x=4))
    ['qw', 'er', 'ty', 'ui']
    

提交回复
热议问题