Hm, let's try:
1 |
str .join(' ', list(' Hello World'))
|
Output:
'Hello World'
Success :-)
Now the first try with bytes:
1 |
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.
Third try:
1 |
bytearray( list (b 'Hello Bytes' ))
|
Output:
bytearray(b'Hello Bytes')
This looks better.
Finally you can use this:
1 |
bytes(bytearray( list (b 'Hello Bytes' )))
|
Output:
b'Hello Bytes'
But you're right. It's not so easy.
Bonus:
Instead of using the list function to construct a list,
use a bytearray. A bytearray is mutable and acts like a list.
1 |
bytes(bytearray(b 'Hello Bytes' ))
|
Output:
b'Hello Bytes'
It's mutable. You can mutate it.
1 2 |
ba = bytearray(b 'Hello Bytes' )
ba[ 0 ] = b 'W'
|
Error:
TypeError: an integer is required
A not so nice solution for it:
Output:
bytearray(b'Wello Bytes')
Extending:
1 2 |
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.
There must be a better way.