刚刚将一个在 CentOS 7 用 Python 2 执行的 Python 程式, 移植到 CentOS 8 的 Python 3 执行, 执行时出现以下报错, 解决方法纪录一下:
TypeError: a bytes-like object is required, not ‘str’
问题出在 Python 2 及 Python 3 在套接字返回值编码上的分别, Python 下的 bytes 及 str 两种资料型态可以用 encode() 及 decode() 互换。
encode() : 把 str 转换成 bytes.
decode() : 把 bytes 转换成 str.
解决方法很简单, 只要把出现问题的地方加入 decode() 可, 例如以下程式码出现问题:
|
1 |
mystr.replace("\n", "") |
改成
|
1 |
mystr.decode().replace("\n", "") |