'Append every n bytes into a byte array

b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A"

How do I append bytes (e.g. b"\xFF") every n bytes (e.g. 2), so it becomes:

b"\x00\x01\xFF\x02\x03\xFF\x04\x05\xFF\x06\x07\xFF\x08\x09\xFF\x0A"


Solution 1:[1]

Iterate on it with a chunk_size of 2, to cut in several pieces of len 2, then join it

value = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A"
result = b'\xFF'.join(value[i:i + 2] for i in range(0, len(value), 2))
print(result)  # b'\x00\x01\xff\x02\x03\xff\x04\x05\xff\x06\x07\xff\x08\t\xff\n'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 azro