简体   繁体   中英

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. 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 ). What I want to do is to somehow parameterize this byte array be able to dynamically pass the 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.

NOTE : The \\xff 's at the end are hardware specific and must be there.

Did you check out the string format docs in python?

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

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, % . I've been told that it either shares code with or mimicks C's stdlib printf style.

# 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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