[英]Prepending bytearray: TypeError: an integer is required
I have two bytearray
s: 我有两个
bytearray
:
ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')
How can I insert ("prepend") ba2
in ba1
? 如何在
ba1
插入(“prepend”) ba2
?
I tried to do: 我试着这样做:
ba1.insert(0, ba2)
But this doesn't seem to be correct. 但这似乎不正确。
Of course I could do following: 我当然可以这样做:
ba2.extend(ba1)
ba1 = ba2
But what if ba1
is very big? 但是如果
ba1
非常大呢? Would this mean unnecessary coping of the whole ba1
? 这是否意味着不必要地应对整个
ba1
? Is this memory-efficient? 这个记忆效率高吗?
How can I prepend a bytearray
? 我怎样才能预先添加一个
bytearray
?
You can do it this way: 你可以这样做:
ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')
ba1 = ba2 + ba1
print(ba1) # --> bytearray(b'Xabcdefg')
To make it more obvious that an insert at the beginning is being done, you might use this instead: 为了使开头的插入更明显,您可以使用它:
ba1[:0] = ba2 # inserts ba2 into beginning of ba1
Also note that as a special case where you know ba2
is only one byte long, this would work: 另请注意,作为一个特殊情况,您知道
ba2
只有一个字节长,这可以工作:
ba1.insert(0, ba2[0]) # valid only if len(ba2) == 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.