Split a string to even sized chunks

后端 未结 8 2155
粉色の甜心
粉色の甜心 2020-11-27 23:05

How would I be able to take a string like \'aaaaaaaaaaaaaaaaaaaaaaa\' and split it into 4 length tuples like (aaaa,aaaa,aaaa

相关标签:
8条回答
  • 2020-11-27 23:27

    Here's another possible solution to the given problem:

    def split_by_length(text, width):
        width = max(1, width)
        chunk = ""
        for v in text:
            chunk += v
            if len(chunk) == width:
                yield chunk
                chunk = ""
    
        if chunk:
            yield chunk
    
    if __name__ == '__main__':
        x = "123456789"
        for i in range(20):
            print(i, list(split_by_length(x, i)))
    

    Output:

    0 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    1 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    2 ['12', '34', '56', '78', '9']
    3 ['123', '456', '789']
    4 ['1234', '5678', '9']
    5 ['12345', '6789']
    6 ['123456', '789']
    7 ['1234567', '89']
    8 ['12345678', '9']
    9 ['123456789']
    10 ['123456789']
    11 ['123456789']
    12 ['123456789']
    13 ['123456789']
    14 ['123456789']
    15 ['123456789']
    16 ['123456789']
    17 ['123456789']
    18 ['123456789']
    19 ['123456789']
    
    0 讨论(0)
  • 2020-11-27 23:34

    Using list comprehension, generator expression:

    >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
    >>> [s[i:i+4] for i in range(0, len(s), 4)]
    ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
    
    >>> tuple(s[i:i+4] for i in range(0, len(s), 4))
    ('aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa')
    
    >>> s = 'a bcdefghi j'
    >>> tuple(s[i:i+4] for i in range(0, len(s), 4))
    ('a bc', 'defg', 'hi j')
    
    0 讨论(0)
提交回复
热议问题