Chunking bytes (not strings) in Python 2 and 3

前端 未结 2 868
旧时难觅i
旧时难觅i 2021-02-14 06:41

This is turning out to be trickier than I expected. I have a byte string:

data = b\'abcdefghijklmnopqrstuvwxyz\'

I want to read this data in c

2条回答
  •  醉酒成梦
    2021-02-14 07:09

    Funcy (a library offering various useful utilities, supporting both Python 2 and 3) offers a chunks function that does exactly this:

    >>> import funcy
    >>> data = b'abcdefghijklmnopqrstuvwxyz'
    >>> list(funcy.chunks(6, data))
    [b'abcdef', b'ghijkl', b'mnopqr', b'stuvwx', b'yz']   # Python 3
    ['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz']        # Python 2.7
    

    Alternatively, you could include a simple implementation of this in your program (compatible with both Python 2.7 and 3):

    def chunked(size, source):
        for i in range(0, len(source), size):
            yield source[i:i+size]
    

    It behaves the same (at least for your data; Funcy's chunks also works with iterators, this doesn't):

    >>> list(chunked(6, data))
    [b'abcdef', b'ghijkl', b'mnopqr', b'stuvwx', b'yz']   # Python 3
    ['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz']        # Python 2.7
    

提交回复
热议问题