Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a Python list with hex elements

Tags:

python

I have this list:

a_list = [0x00, 0x00, 0x00, 0x00]

When I print it, I get:

print a_list
[0, 0, 0, 0]

But I want:[0x0, 0x0, 0x0, 0x0] or [0x00, 0x00, 0x00, 0x00], it doesn't matter for now.

I've tried to create a function such as:

def hex_print(the_list):
     string = '['
     for element in the_list:
         if(the_list.index(element) < len(the_list)):
             print(str(the_list.index(element)))
             string = string + hex(element) + ', '
         else:
             print(str(the_list.index(element)))
             string = string + hex(element) + ']'
     print string

But every time the printed message is:

[0x0, 0x0, 0x0, 0x0,

I think that the_list.index(element) always returns the first occurrence of element in the_list and not the actual position of the element. Is there a way where I can get the actual position of the element?

like image 523
Manaure Garcia Avatar asked Sep 13 '13 10:09

Manaure Garcia


2 Answers

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

This has the advantage of not putting quotes around all the elements, so it produces a valid literal for a list of numbers.

like image 57
user2357112 supports Monica Avatar answered Oct 05 '22 13:10

user2357112 supports Monica


Try the following:

print [hex(x) for x in a_list]

The output shall be something like: http://codepad.org/56Vtgofl

like image 44
hjpotter92 Avatar answered Oct 05 '22 11:10

hjpotter92