Reputation: 639
I've got a list of hex strings.
mylist = ['0xff', '0x34', '0x95', '0x11']
I'd like to get this list into another list, but in hex format. Thus the list should look something like this.
myhexlist = ['\xff', '\x34', '\x95', '\x11']
What I've tried:
#!/usr/bin/env python
myhexlist = []
mylist = ['0xff', '0x34', '0x95', '0x11']
for b in mylist:
myhexlist.append( hex(int(b,16)) )
print myhexlist
Which does not produce the desired output.
Upvotes: 0
Views: 162
Reputation: 44321
You want to use chr
rather than hex
(which just reverses the transformation).
Also, it's more efficient to use a list comprehension rather than a loop in which you're appending to a list.
>>> myhexlist = [chr(int(hex_str, 16)) for hex_str in mylist]
>>> myhexlist
['\xff', '4', '\x95', '\x11']
(obviously you're not going to get a \x##
for a printable character).
Upvotes: 2