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.
-
stackoverflow.com/questions/7585435/…Petronella– Petronella2021-05-10 09:05:05 +00:00Commented May 10, 2021 at 9:05
-
2Does this answer your question? Best way to convert string to bytes in Python 3?Petronella– Petronella2021-05-10 09:05:36 +00:00Commented May 10, 2021 at 9:05
-
Thank you for your answer. I am aware of this function. What I am looking for is not only that but the segmentation in chunks by bytes. There is probabily already a solution for this.Pm740– Pm7402021-05-10 12:09:32 +00:00Commented May 10, 2021 at 12:09
Add a comment
|
2 Answers
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)]
1 Comment
Pm740
Thank you for your response. Didn't knew that lists in python consider the fact that the last part is a overflow.
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
Pm740
Thank you for your answer. Didn't knew that python copes with overflow in index...