
python 3 编码问题详解
在 python 3 中解决编码问题时,需要格外注意 bytes 和 str 对象。
问题中提到的报错信息 "typeerror: a bytes-like object is required, not 'str'" 的意思是,需要传递一个字节对象,而不是字符串对象。即使 data 已经是 bytes 类型,但 ctime() 编码后的结果仍然是字符串,导致了这个错误。
为了解决这个问题,需要将 ctime() 编码的结果也转换为 bytes 类型。完整代码如下:
立即学习“Python免费学习笔记(深入)”;
# 服务器
from socket import *
from time import ctime
HOST = ''
PORT = 21507
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connected from:', addr)
while True:
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
print(type(data))
tcpCliSock.send(('[{}] {}'.format(ctime().encode('utf-8'), data.decode()).encode()))
tcpCliSock.close()通过将 ctime() 编码后的结果转换为 bytes 类型,我们解决了编码问题,服务器可以正确地接收和发送数据。
以上就是Python 3 中如何解决 "TypeError: a bytes-like object is required, not 'str'" 编码错误?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号