繁体   English   中英

Python 2.7 中的字符串格式字节数组

[英]String format byte array in Python 2.7

我对 python 很陌生,我目前正在玩pyserial ,我基本上做的是通过 UART 发送简单的命令。 我拥有的一个简单命令是:

b'page 0\xff\xff\xff'

它基本上对硬件说“以 0 索引进入页面”(这是一个Nextion 显示器)。 我想要做的是以某种方式参数化这个字节数组能够动态传递0 我在互联网上阅读了不同的主题,首先将其设为字符串,然后再使用bytearray,但我想知道是否无法使用字符串插值或其他方式将其应用于此处。

注意末尾\\xff是特定于硬件的,必须在那里。

您是否签出了python中的字符串格式文档?

pageNum = 0
b'page {}\xff\xff\xff'.format(pageNum)

https://docs.python.org/3.4/library/string.html#string-formatting

如果有人仍然对我如何实现自己的目标感兴趣,那么我可以采用以下解决方案:

def __formatted_page_command(self, pageId): 
    # This is the representation of 'page 0\xff\xff\xff'. What we do here is to dynamically assign the page id. 
    commandAsBytesArray = [0x70,0x61,0x67,0x65,0x20,0x30,0xff, 0xff, 0xff] 
    commandAsBytesArray[5] = ord(str(pageId)) 
    return bytes(commandAsBytesArray)

因此,通过这种方式,我可以动态获得:

b'page 0\xff\xff\xff'
b'page 1\xff\xff\xff'
b'page 2\xff\xff\xff'

只需致电

self.__formatted_page_command(myPageId)

我正在寻找其他东西,但在结果中发现了这一点。 我情不自禁地添加了一个对我来说似乎如此标准的解决方案。

在 Python 2 中,有一个比.format更快的低级格式化构造,它以内置 str 的mod运算符%的形式内置于语言中。 有人告诉我,它要么与 C 的 stdlib printf 风格共享代码,要么模仿 C 的 stdlib printf 风格。

# you're pretty screwed if you have > 255 pages
# or if you're trying to go to the last page dynamically with -1
assert 0 <= pageId <= 0xff, "page out of range"
return b'page %s\xff\xff\xff' % pageId

还有其他选择,但我更喜欢老派的简单性。

暂无
暂无

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

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