TypeError:解码十六进制字符串时的奇数长度字符串

Phi*_*Bot 2 python string hex decode python-2.7

我确保字符串被剥离,我仍然得到奇数字符串问题.有人可以告诉我我做错了什么吗?

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string
>>> 
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 8

字符串中的空格使decode方法混乱.如果删除它们,您的代码将起作用:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.replace(' ', '').decode('hex')
'\xff\xf9\xff\x00\x00\xfa\xff\xf7\xff\xf4\xff\xf6\xff\xf7\xff\xf6\xff\xfd\xff\x05\x00\x03\x00\x06\x00\x05\x00\x04\x00\x06\x00\x06\x00\x03\x00\xfb\xff\x02\x00\x0b'
>>>
Run Code Online (Sandbox Code Playgroud)

或者,如果您必须拥有它们,请使用str.join和列表理解:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> ' '.join([x.decode('hex') for x in toSend.split()])
'\xff \xf9 \xff \x00 \x00 \xfa \xff \xf7 \xff \xf4 \xff \xf6 \xff \xf7 \xff \xf6 \xff \xfd \xff \x05 \x00 \x03 \x00 \x06 \x00 \x05 \x00 \x04 \x00 \x06 \x00 \x06 \x00 \x03 \x00 \xfb \xff \x02 \x00 \x0b'
>>>
Run Code Online (Sandbox Code Playgroud)