Python Forum

Full Version: Bytearray substitution
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone!

I want to make an array of bytes like this: my_array= b'\x01\x00\x00\x01\xff\xff'
Then substitute the 4th element to b'\x50'
if I have a int variable A=50 how I can do to change the 4th element to A

I have tried A=A.to_bytes() and then myarray[3]=A but it didnt work.

any ideas of how to do this?

thank you.
That is not a byte array, rather it is a byte object which is immutable. In order to be able to assign new values, you need to make it into a byte array first. my_array = bytearray(b'\x01\x00\x00\x01\xff\xff')
Now you can assign values to the array my_array[3] = A