关于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)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DLANDML

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值