Insert bytearray into bytearray Python

夙愿已清 提交于 2020-06-25 05:28:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!