在 Python 3.5 中,使用套接字,我有:
message = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n'
s.send(message.encode())
我怎样才能在一行中做到这一点?我问是因为我有:
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
但是在 Python 中需要 3.5 个字节,而不是字符串,所以这给出了错误:
builtins.TypeError: a bytes-like object is required, not 'str'
我不应该使用发送吗?
最佳答案
str
,text 的类型,不同于bytes
,八位字序列的类型。要简洁地从一个转换为另一个,您可以内联对 encode
的调用(就像您可以使用任何函数调用一样)...
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
.. 请记住,指定您要使用的编码通常是个好主意...
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('ascii'))
...但使用 bytes literal 更简单.在字符串前加上 b
:
s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
但是你知道什么更简单吗?让其他人为您做 HTTP。您是否考虑过使用服务器,例如 Flask ,甚至 the standard library ,构建您的应用程序?
关于python - 如何在一行中的套接字连接的发送方法中将字符串编码为字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092256/