yanu 发表于 2014-11-17 23:17

python3的二进制转文本问题

事情是这样的: struct.pack在python3上返回个bytes,我试着解码成utf-8 或者ascii都报错,这可咋办

在python2上:>>> msg = struct.pack("I",socket.htonl(len(text))) + text
>>>
在python3上:>>> msg = struct.pack("I",socket.htonl(len(text))) + text
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
>>>
>>> struct.pack("<I",socket.htonl(len(text))).decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 3: invalid start byte

>>> struct.pack("<I",socket.htonl(len(text))).decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xac in position 3: ordinal not in range(128)
>>>

yanu 发表于 2014-11-18 09:24

:-L把str转成bytes再拼接,居然过了,后面的功能貌似也没受影响msg = struct.pack("I",socket.htonl(len(text))) + text.encode()
页: [1]
查看完整版本: python3的二进制转文本问题