'Is there a way to print all values of a complex structure in hexadecimal format without loops, in python?

I sometimes have to print complex structures, such as list of tuples, say:

lst = [(101, 102), (103, 104)]
print(lst)
[(101, 102), (103, 104)]

I want the print to be formated in hexadecimal, ideally something like:

print(lst.hex())
[(0x65, 0x66), (0x67, 0x68)]

If I had a simple list, I could write:

>>> a_list = range(4)
>>> print '[{}]'.format(', '.join(hex(x) for x in a_list))
[0x0, 0x1, 0x2, 0x3]

So I assume with nested list comprehension or multivariable ones, I could managed it thought I barely know how thought I have read several Q/A on the subject here.

So, is there a simple way to do it, independent of the structure complexity?



Solution 1:[1]

Using Andrew Ryan's idea, here is a solution that relies on recursion rather than iteration:

lst = [(101, 102), (103, 104)]


def recursive_convert(l, i=0):
    if type(l) == list:
        x = l.pop(i)
        l.insert(i, recursive_convert(x))
        if i+1 < len(l):
            return recursive_convert(l,i+1)
        return l
    elif type(l) == tuple:
        l = (hex(l[0]), hex(l[1]))
        return l
    


print(recursive_convert(lst))

Note that this assumes some things, like the number of elements in the tuple as well as knowledge of the data structure that's in the list.

Output:

[('0x65', '0x66'), ('0x67', '0x68')]

Solution 2:[2]

how about using list comprehension?

lst = [(101, 102), (103, 104)]
print([(hex(x),hex(y)) for x,y in lst])

output:

>> [('0x65', '0x66'), ('0x67', '0x68')]

or you can use NumPy printoption:

import numpy as np
lst = [(101, 102), (103, 104)]
np.set_printoptions(formatter={'int':hex})
print(np.array(lst))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard K Yu
Solution 2