简体   繁体   English

在特定位置查找字节 PYTHON

[英]Find bytes at specific position PYTHON

I have a simple function to read bytes from serial port.我有一个简单的函数来从串行端口读取字节。

Simply code looks like简单的代码看起来像

read_bytes = serial.read(5)

After that I print a result and for example I have之后我打印了一个结果,例如我有

b'\\x01\\x02\\x03\\x04\\x05'

There is an option to catch bytes at specific position ?有一个选项可以在特定位置捕获字节? For example If I want to print byte at second position it should print for me b'\\x02' .例如,如果我想在第二个位置打印字节,它应该为我打印b'\\x02' I read documentation but functions find and index do different stuff.我阅读文档,但函数findindex做不同的事情。

You can treat the bytes class as an iterable, and you can access its elements as you would with a simple string like:您可以将bytes类视为可迭代的,并且可以像使用简单的字符串一样访问其元素,例如:

read_bytes = b'\x01\x02\x03\x04\x05'
read_bytes[2]
# 3
read_bytes[0]
# 1

So just use list indexing to access an element with a specific index.所以只需使用列表索引来访问具有特定索引的元素。

Update:更新:

In case you want to retrieve the element as a bytes object you can slice it from the sequence:如果您想将元素作为bytes对象检索,您可以从序列中对其进行切片:

read_bytes[2:3]
# b'\x03'
read_bytes[0:1]
# b'\x01'

A more verbose way is to get the element and cast it as bytes更详细的方法是获取元素并将其转换为bytes

bytes([read_bytes[2]])

Note: you have to pass the value in an iterable otherwise bytes will return a sequence of null bytes with a length of the integer value it received.注意:您必须在可迭代对象中传递值,否则bytes将返回一个空字节序列,其长度为它收到的整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM