Mar-01-2018, 01:44 AM
if i want to convert a string to a list then back, again, it's rather easy. if i want to do the same with a byte string it's not. anyone know a way that can be done to both using the same code for either?
str.join('', list('Hello World'))
Output:'Hello World'
Success :-)bytes.join(b'', list(b'Hello Bytes'))
Error:TypeError: sequence item 0: expected a bytes-like object, str found
This is the problem with the representation. Iterating over bytes returns integers.bytearray(list(b'Hello Bytes'))
Output:bytearray(b'Hello Bytes')
This looks better.bytes(bytearray(list(b'Hello Bytes')))
Output:b'Hello Bytes'
But you're right. It's not so easy.bytes(bytearray(b'Hello Bytes'))
Output:b'Hello Bytes'
It's mutable. You can mutate it.ba = bytearray(b'Hello Bytes') ba[0] = b'W'
Error:TypeError: an integer is required
A not so nice solution for it:ba[0] = ord(b'W') ba
Output:bytearray(b'Wello Bytes')
Extending:ba.extend(b' This is the next Chunk') ba
Output:bytearray(b'Wello Bytes This is the next Chunk')
But i know what you mean. Handling with bytes a bit pain in the ass.