将字符串分割为2字符字符串的列表
我有一串十六进制的数字,比如:1a2b3c4d5e6f7g,但它更长。我想把它分成每两个字符一组的十六进制值,然后再把这些值转换成ASCII字符。
3 个回答
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
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'
5
那binascii.unhexlify(hexstr)呢?
可以查看binascii模块的文档:http://docs.python.org/library/binascii.html