Reputation: 21
i am trying to split this udp packet and i want specfic packets 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...
so:
if '0 ' in line:print line;
line = line.split('0 ')[1]
yields:
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...\
a trailing zero missing in each line
Upvotes: 1
Views: 130
Reputation: 1737
You're splitting the line on a string which appears more than once. Note:
>>> 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....']
When you split a string, the string you split on is not included in the resulting list elements. In this case, you can restrict it to only split on the first occurrence:
>>> 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....']
This might still not be what you want, as now the second element of the list still contains the ASCII dump section. In that case, you probably need to split again on the multiple spaces which appear between the hex dump and the ASCII dump.
Upvotes: 1
Reputation: 168626
One of these might help:
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
Upvotes: 1