Skip to main content
 首页 » 编程设计

python之如何从python中的s字符串中删除前4个字节

2025年05月04日19mfrbuaa

我得到一个字符串格式的特殊数据包,它有 32 字节的 header 和主体包含一个或多个条目,每个条目由 90 字节组成。

我想用 python 处理这个字符串。我可以像 sock 一样读取前 32 个字节的 header ,然后将其从字符串中取出,然后继续读取第一个条目的 90 个字节吗?

类似于:

str.read(32) # => "x01x02..." 
str.read(90) # => "x02x05..." 

请您参考如下方法:

您可以使用 StringIO像读取文件一样读取字符串

>>> import StringIO 
>>> s = 'Hello, World!' 
>>> sio = StringIO.StringIO(s) 
>>> sio.read(6) 
'Hello,' 
>>> sio.read() 
' World!' 

我还建议您看一下 struct帮助解析二进制数据的模块

>>> from struct import * 
>>> pack('hhl', 1, 2, 3) 
'\x00\x01\x00\x02\x00\x00\x00\x03' 
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') 
(1, 2, 3) 

你使用格式字符串定义数据的格式,所以上面例子中的'hhl'是short(2字节),short(2字节),int(4字节) 。它还支持在格式字符串中指定字节顺序。

例如,如果您的 header 格式是 uint, 4 byte str, uint, uint, ushort, ulong:

>>> import struct 
>>> data = ''.join(chr(i) for i in range(128)) * 10 
>>> hdr_fmt = 'I4sIIHL' 
>>> struct.calcsize(hdr_fmt) 
32 
>>> struct.unpack_from(hdr_fmt, data, 0) 
(50462976, '\x04\x05\x06\x07', 185207048, 252579084, 4368, 2242261671028070680)