首页 > 解决方案 > Is there a way to item assignment for bytes object?

问题描述

I am trying to assign bytes to a portion of pcap data(using slice operation) as below. I am getting "TypeError: 'bytes' object does not support item assignment" when try to assign data [a[8:24] = new5]. If not supported, is there any way?

code:

x = rdpcap("ref.pcap")
for packet in x:
    a = (bs.hexlify(bytes(packet.load)))
    TTF = a[8:24]
    print ("T1",TTF)
    new0 = (TTF.decode('utf-8'))
    print ("T1-decode",new0)
    print ("T1-dec",int(new0, base=16))
    new4 = hex(int(time.time()))[2:]
    print ("new4",new4)
    new5 = bytes(new4, encoding='utf8')
    print ("new5",new5)
    print (a[8:24])
    a[8:24] = new5

output:

T1 b'60ac7bd500000000'
T1-decode 60ac7bd500000000
T1-decimal 6966078878393565184
new4 60af6be2
new5 b'60af6be2'
b'60ac7bd500000000'
Traceback (most recent call last):
  File "<stdin>", line 15, in <module>
TypeError: 'bytes' object does not support item assignment

标签: pythonpython-3.x

解决方案


字节串是不可变的。你需要复印一份。

data = b'this is a test'
new_data = data[:5] + b'was' + data[7:]
# or, using join():
# new_data = b''.join((data[:5], b'was', data[7:]))
new_data

输出:

b'this was a test'

或者,您可以使用字节数组:

data = bytearray(b'this is a test')
data[5:7] = b'was'
data

输出:

bytearray(b'this was a test')

推荐阅读