问题
I'm trying to insert one byte array into another at the beginning. Here's a simple example of what I'm trying to accomplish.
import struct
a = bytearray(struct.pack(">i", 1))
b = bytearray(struct.pack(">i", 2))
a = a.insert(0, b)
print(a)
However this fails with the following error:
a = a.insert(0, b)
TypeError: an integer is required
回答1:
bytearray
is a sequence-type, and it supports slice-based operations. The "insert at position i
" idiom with slices goes like this x[i:i] = <a compatible sequence>
. So, for the fist position:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[0:0] = b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')
For the third position:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[2:2] = b
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x02\x00\x01')
Note, this isn't equivalent to .insert
, because for sequences, .insert
inserts the entire object as the ith element. So, consider the following simple example with lists:
>>> y = ['a','b']
>>> x.insert(0, y)
>>>
>>> x
[['a', 'b'], 1, 2, 3]
What you really wanted was:
>>> x
[1, 2, 3]
>>> y
['a', 'b']
>>> x[0:0] = y
>>> x
['a', 'b', 1, 2, 3]
回答2:
>>> a = bytearray(struct.pack(">i", 1))
>>> b = bytearray(struct.pack(">i", 2))
>>> a = b + a
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')
回答3:
Bytearray are mutable sequence of single bytes (integers), so bytearray only accepts integers that meet the value restriction 0 <= x <= 255):
>>> a = bytearray(struct.pack(">i", 1))
>>> b = bytearray(struct.pack(">i", 2))
>>> a.insert(0,b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> a=b+a
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')
>>>a[:2]=b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x01')
来源:https://stackoverflow.com/questions/46331220/insert-bytearray-into-bytearray-python