如何在一行中的套接字连接的发送方法中将字符串编码为字节?

How do I encode a string to bytes in the send method of a socket connection in one line?

在 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'

我不应该使用发送吗?

使用这个:

s.send(b'your text')

在字符串前添加b会将其转换为bytes

在左引号前放置 bB 会将 str 文字更改为 bytes 文字:

s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')

strtext的类型,与bytes8位序列的类型不同单词。要简洁地从一个转换为另一个,您可以内联对 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, or even the standard library 来构建您的应用程序?