-1

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.

3

2 Answers 2

1

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. Didn't knew that lists in python consider the fact that the last part is a overflow.
1

You can use the chunks method in the funcy library. An example would be:

import funcy

text = 'samplestringwithletters'
btext = text.encode('utf-8')

chunked_text = list(funcy.chunks(3,btext))
print(chunked_text)

Which yields:

[b'sam', b'ple', b'str', b'ing', b'wit', b'hle', b'tte', b'rs']

1 Comment

Thank you for your answer. Didn't knew that python copes with overflow in index...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.