Python 3.5.2 TypeError: a bytes-like object is required, not 'str’问题解决方案

本文介绍了一个常见的Python类型错误——发送HTTP响应时将str类型误作为bytes类型使用的问题,并提供了具体的解决方案,即使用encode()方法将字符串编码为bytes。

运行环境Mac  Python 3.5.2

Q:

http_response = """\

HTTP/1.1 200 OK

 

Hello, World!

"""

client_connection.sendall(http_response)

 

TypeError: a bytes-like object is required, not 'str'

类型错误,需要的是一个byte类型,不是str类型

A:

http_response = """\

HTTP/1.1 200 OK

 

Hello, World!

"""

encode_http_response = http_response.encode()

client_connection.sendall(encode_http_response)

 

Expand:

str通过encode()方法可以编码为指定的bytes

反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:

转载于:https://www.cnblogs.com/izhanglei/p/7590608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值