python - 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
解决方案
字节串是不可变的。你需要复印一份。
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')
推荐阅读
- makefile - Make:目标选择
- c# - 变量类型列表
在对象中,我怎样才能制作这个对象的列表 - r - 处理带有多个 csv 列表的两行标题
- mysql - MacOS Mojave - brew install mysql@5.7 - 用户'root'@'localhost'的访问被拒绝
- python - 如何检查一个数组是否在 Python 的数组列表中?
- node.js - module.exports 导出默认值:如何以正确的方式重写?
- python - 优先考虑来自 csv 的重复项
- linux - 两个默认网关上的路由问题
- reporting-services - 从 Reporting Services 迁移到 SSDT
- kubernetes - Kubernetes 不创建证书