关于python2与python3编码方式转换的问题

理解1:

/tmp/ python3
Python 3.2.3 (default, Feb 20 2013, 14:44:27) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 
>>> f1 = open("unicode.txt", 'r').read()
>>> print(f1)
你好
 
>>> f2 = open("unicode.txt", 'rb').read() #二进制方式打开
>>> print(f2)
b'\xe5\xaf\x92\xe5\x86\xb7\n'
>>> f2.decode()
'你好\n'
>>> f1.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'



====================================================》》》》》
python 3中只有unicode str,所以把decode方法去掉了。python3环境中,f1已经是unicode str了,不用decode。

如果文件内容不是unicode编码的,要先以二进制方式打开,读入比特流,再解码。

参考文献:https://blog.csdn.net/qq_34343669/article/details/81874065

理解2:

解决问题
TypeError: a bytes-like object is required, not 'str'


解决思路
问题出在python3.5和Python2.7在套接字返回值解码上有区别:
python bytes和str两种类型可以通过函数encode()和decode()相互转换,
str→bytes:encode()方法。str通过encode()方法可以转换为bytes。
bytes→str:decode()方法。如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法。

解决方法
将line.strip().split(",")  改为  line.decode().strip().split(","),大功告成!

正确写法:(字符串转16进制)

server_reply = binascii.hexlify(s.recv(1024)).decode()
print(server_reply)

猜你喜欢

转载自blog.csdn.net/l641208111/article/details/116028058