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.
Asked
Active
Viewed 371 times
-1
-
https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 – Petronella May 10 '21 at 09:05
-
2Does this answer your question? [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3) – Petronella May 10 '21 at 09: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 May 10 '21 at 12:09
2 Answers
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']

boxhot
- 189
- 5
-
1Thank you for your answer. Didn't knew that python copes with overflow in index... – Pm740 May 11 '21 at 07:08
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)]

Ajay Rathore
- 124
- 1
- 7
-
1Thank you for your response. Didn't knew that lists in python consider the fact that the last part is a overflow. – Pm740 May 11 '21 at 06:53