将字符串拆分为2char字符串列表

时间:2011-09-09 14:05:50

标签: python hex ascii

我有一个十六进制流,如:1a2b3c4d5e6f7g但更长 我想将它拆分为列表中的2char十六进制值,然后将它们转换为ascii。

3 个答案:

答案 0 :(得分:5)

binascii.unhexlify(hexstr)怎么样? 请参阅binascii模块的文档:http://docs.python.org/library/binascii.html

答案 1 :(得分:3)

在Python 2.x中,您可以使用binascii.unhexlify

>>> import binascii
>>> binascii.unhexlify('abcdef0123456789')
'\xab\xcd\xef\x01#Eg\x89'

在Python 3中,只使用内置bytes类型的方法更为优雅:

>>> bytes.fromhex('abcdef0123456789')
b'\xab\xcd\xef\x01#Eg\x89'

答案 2 :(得分:2)

一个班轮:

a = "1a2b3c"
print ''.join(chr(int(a[i] + a[i+1], 16)) for i in xrange(0, len(a), 2))

说明:

xrange(0, len(a), 2) # gives alternating indecis over the string
a[i] + a[i+1]        # the pair of characters as a string
int(..., 16)         # the string interpreted as a hex number
chr(...)             # the character corresponding to the given hex number
''.join()            # obtain a single string from the sequence of characters