简体   繁体   中英

Printing values with tabulate in hex

I've been following this answer to print an array as a nice table. This works except that it prints values in decimal. How do I print values in hex? Here is the code:

from tabulate import tabulate

headers = ['array #', 'TX', 'RX']
tx_buffer = [0xCA, 0xFE, 0x80, 0x80, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00]

rx_buffer = [0]*54

idx = range(0, 54, 1)
table = zip(idx, tx_buffer, rx_buffer)

print("\n")
print(tabulate(table, headers=headers))
print("\n")

You can use hex or format

tx_buffer=[hex(i) for i in tx_buffer] 
             or

tx_buffer=[format(i, '#x') for i in tx_buffer]

hex(x) :

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”

format(value[, format_spec]) :

Convert a value to a “formatted” representation, as controlled by format_spec

Output:

array #  TX      RX
---------  ----  ----
        0  0XCA     0
        1  0XFE     0
        2  0X80     0
        3  0X80     0
        4  0X0      0
        5  0X0      0
        6  0X0      0
        7  0X0      0

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