Python 将字符串拆分为2char字符串列表
我有一个十六进制流,比如:1a2b3c4d5e6f7g,但更长Python 将字符串拆分为2char字符串列表,python,hex,ascii,Python,Hex,Ascii,我有一个十六进制流,比如:1a2b3c4d5e6f7g,但更长 我想将其拆分为列表中的2char十六进制值,然后将其转换为ascii。关于binascii.unexlify(hexstr)? 请参阅binascii模块的文档:一行程序: 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
我想将其拆分为列表中的2char十六进制值,然后将其转换为ascii。关于
binascii.unexlify(hexstr)
?请参阅binascii模块的文档:一行程序:
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
在Python 2.x中,您可以使用:
在Python 3中,有一种更优雅的方法,只使用内置的bytes
类型:
>>> bytes.fromhex('abcdef0123456789')
b'\xab\xcd\xef\x01#Eg\x89'
+1
binascii.unhexlify('7573652062696E617363692E756E68655786C696679')
给出了'use binascii.unhexlify'
包含字符“g”的“hex流”的副本确实是一种非常有趣的动物。它似乎还有另一个名字:a2b_hex>>binascii.a2b_hex('abcdef0123456789')[0]:'\xab\xcd\xef\x01#Eg\x89'
>>> bytes.fromhex('abcdef0123456789')
b'\xab\xcd\xef\x01#Eg\x89'