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

运行环境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()方法:

posted @ 2017-09-25 10:04  izhangleinb  阅读(795)  评论(0编辑  收藏  举报