简体   繁体   English

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

[英]String format byte array in Python 2.7

I am quite new to python and I am currently playing around with pyserial and what I am basically doing is sending simple commands via UART.我对 python 很陌生,我目前正在玩pyserial ,我基本上做的是通过 UART 发送简单的命令。 A simple command that I have is:我拥有的一个简单命令是:

b'page 0\xff\xff\xff'

which basically says to the hardware "Go on page with index of 0" (It is a Nextion display ).它基本上对硬件说“以 0 索引进入页面”(这是一个Nextion 显示器)。 What I want to do is to somehow parameterize this byte array be able to dynamically pass the 0 .我想要做的是以某种方式参数化这个字节数组能够动态传递0 I've read different topics on the internet of first making it a string and later one use bytearray but I was wondering if it is not possible to apply it here somehow using string interpolation or something.我在互联网上阅读了不同的主题,首先将其设为字符串,然后再使用bytearray,但我想知道是否无法使用字符串插值或其他方式将其应用于此处。

NOTE : The \\xff 's at the end are hardware specific and must be there.注意末尾\\xff是特定于硬件的,必须在那里。

Did you check out the string format docs in python? 您是否签出了python中的字符串格式文档?

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

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

If someone is still interested of how I achieved my goal, I came to the following solution: 如果有人仍然对我如何实现自己的目标感兴趣,那么我可以采用以下解决方案:

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)

So, in this way, I can dynamically get: 因此,通过这种方式,我可以动态获得:

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

just by calling 只需致电

self.__formatted_page_command(myPageId)

I was searching for something else but found this in results.我正在寻找其他东西,但在结果中发现了这一点。 I could not help myself but to add a solution that seems so standard to me.我情不自禁地添加了一个对我来说似乎如此标准的解决方案。

In Python 2 there is a lower level formatting construct that is faster than .format that is built into the language in the form of the builtin str's mod operator, % .在 Python 2 中,有一个比.format更快的低级格式化构造,它以内置 str 的mod运算符%的形式内置于语言中。 I've been told that it either shares code with or mimicks C's stdlib printf style.有人告诉我,它要么与 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

There are other options but I prefer old-school simplicity.还有其他选择,但我更喜欢老派的简单性。

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

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