0

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.

2
  • Why not just replace 0x with \x? For example, myhexlist = [i.replace("0x", "\\x") for i in mylist]. Commented Oct 16, 2013 at 20:00
  • That will keep the data type the same as a string. Nicholas's answer is what I was attempting to do. Commented Oct 16, 2013 at 20:13

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.