Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串拆分为2char字符串列表_Python_Hex_Ascii - Fatal编程技术网

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

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

我有一个十六进制流,比如: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 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'