Search code examples
pythonpython-3.xmemory-segmentationtext-segmentation

How to convert plain text in segmented chunks (Bytes) in python?


Is there a simple way to convert plain text into a segmented array of chunks in python? Each chunk should be for example 16 Bytes. If the last part of the plain text is smaller than 16 Bytes it should can be filled in a smaller chunk.


Solution

  • If you would like to achieve the same without external library then you could use bytes or bytesarray.

    text = 'some text to convert in the chunks'
    bin_str = bytes(text.encode('utf-8'))
    n = 16 #no. of bytes for chunks    
    chunks = [bin_str[i:i+n] for i in range(0, len(bin_str), n)]