I'm trying to append the contents of a list (which only contains hex numbers) to a bytearray. Right now I'm doing this and it works:
payload = serial_packets.get()
final_payload = bytearray(b"StrC")
final_payload.append(len(payload))
for b in payload:
final_payload.append(b)
However, I believe it's not very Pythonic. Is there a better way to do this?
tldr; How can I append payload to final_payload in a more Pythonic way?
To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
To join a list of Bytes, call the Byte. join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError , so make sure to call it on a Byte object b' '. join(...)
The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
You can extend, you don't need to iterate over payload:
final_payload.extend(payload)
Not sure you want final_payload.append(len(payload))
either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With