Prepending bytearray in Python 3, TypeError: integer required
I have two bytes:
ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')
how can i preend ba2 into ba1?
I tried to do:
ba1.insert(0, ba2)
But that doesn't seem right.
Of course, I could do the following:
ba2.extend(ba1) ba1 = ba2
But what if ba1 is very large? Does this mean that there is no need to deal with all ba1? Is this memory efficient?
How can I add bytearray?
thank
+3
source to share
1 answer
You can do it like this:
ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')
ba1 = ba2 + ba1
print(ba1) # --> bytearray(b'Xabcdefg')
To make it more obvious to do the insert at the start, you can use this instead:
ba1[:0] = ba2 # inserts ba2 into beginning of ba1
Also note that as a special case, when you only know ba2
one byte, this will work:
ba1.insert(0, ba2[0]) # valid only if len(ba2) == 1
+7
source to share