简体   繁体   中英

How do you convert a hex string into hex?

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.

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

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