1

我正在尝试拆分此 udp 数据包,我想要特定数据包 conating “xx ff”

0000  xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 00   >.:1....X. A....
0010  02 de 01 11 05 00 02 00 00 ff 3c ff 00 00 34 2d   .........K<....-
0020  00 44 00 00 00 00 00 00 0a x3 00 01 00 60 00 00   ................
0030  00 00 89 70 62 00 02 00 00 76 98 05 8b            ..i.b....v...

所以:

if '0  ' in line:print line;
    line = line.split('0  ')[1]

产量:

0000  xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 0   >.:1....X. A....
0010  02 de 01 11 05 00 02 00 00 ff 3c ff 00 00 34 2d   .........K<....-
0020  00 44 00 00 00 00 00 00 0a x3 00 01 00 60 00 0   ................
0030  00 00 89 70 62 00 02 00 00 76 98 05 8b            ..i.b....v...\

每行中缺少尾随零

4

2 回答 2

1

您将在多次出现的字符串上分割线。笔记:

>>> s = "0000  xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 0   >.:1....X. A...."
>>> s.split("0  ")
['000', 'xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 ', ' >.:1....X. A....']

拆分字符串时,您拆分的字符串不包含在结果列表元素中。在这种情况下,您可以将其限制为仅在第一次出现时拆分:

>>> s.split("0  ", maxsplit=1)
['000', 'xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 0   >.:1....X. A....']

这可能仍然不是您想要的,因为现在列表的第二个元素仍然包含 ASCII 转储部分。在这种情况下,您可能需要再次拆分出现在十六进制转储和 ASCII 转储之间的多个空格。

于 2013-09-11T23:18:16.787 回答
1

其中之一可能会有所帮助:

packet='''0000  xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 00   >.:1....X. A....
0010  02 de 01 11 05 00 02 00 00 ff 3c ff 00 00 34 2d   .........K<....-
0020  00 44 00 00 00 00 00 00 0a x3 00 01 00 60 00 00   ................
0030  00 00 89 70 62 00 02 00 00 76 98 05 8b            ..i.b....v...'''


# Using a generator expression
result =  ' '.join(' '.join(line[5:55].split()) for line in packet.splitlines())
print 'xx ff' in result  # true
print 'x3' in result     # true
print '72' in result     # false

# Using a loop
result = []
for line in packet.splitlines():
    result.extend(line[5:55].split())
result = ' '.join(result)
print 'xx ff' in result  # true
print 'x3' in result     # true
print '72' in result     # false
于 2013-09-11T21:47:42.527 回答