python - 在Python中分割字符串时丢失了字符串

标签 python

我正在尝试拆分此 udp 数据包,并且我想要包含“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...\

每行缺少尾随零

最佳答案

其中之一可能有帮助:

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

关于python - 在Python中分割字符串时丢失了字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751098/

相关文章:

python - 在哪里实例化 Django/Python 应用程序的几个部分中使用的对象?

Python - 使用 Osmnx 包获取 "TypeError: argument of type ' CRS' 不可迭代

python - 为什么简单的与门神经网络在没有 BIAS 的情况下无法工作?

Python无法导入libsvm

python - ElasticSearch/Python 动态过滤器数量

python - 如何用一个线程监听redis的所有订阅 channel ?

python - "Redeclared s defined above without usage"

python - 添加在 TensorFlow 中检测到的对象

python - 在 Appium Python 中尝试 if ellif

python - scipy.optimize.curve_fit 错误 - 函数结果不是正确的 float 组