如何在一行中的套接字连接的发送方法中将字符串编码为字节? [英] How do I encode a string to bytes in the send method of a socket connection in one line?
问题描述
在 Python 3.5 中,使用套接字,我有:
In Python 3.5, using sockets, I have:
message = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n'
s.send(message.encode())
我怎样才能在一行中做到这一点?我问是因为我有:
How can I do that in one line? I ask because I had:
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
但在 Python 中需要 3.5 个字节,而不是字符串,因此会出现错误:
but in Python 3.5 bytes are required, not a string, so this gives the error:
builtins.TypeError: a bytes-like object is required, not 'str'
我不应该使用发送吗?
推荐答案
str
,text的类型,与bytes
不一样>,八位字序列的类型.为了简洁地从一个转换到另一个,您可以将调用内联到 encode
(就像您可以使用任何函数调用一样)...
str
, the type of text, is not the same as bytes
, the type of sequences of eight-bit words. To concisely convert from one to the other, you could inline the call to encode
(just as you could with any function call)...
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
...记住,指定要使用的编码通常是个好主意...
.. bearing in mind that it's often a good idea to specify the encoding you want to use...
s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('ascii'))
...但使用字节文字更简单.用 b
前缀你的字符串:
... but it's simpler to use a bytes literal. Prefix your string with a b
:
s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
但你知道什么更简单吗?让别人为你做 HTTP.你有没有想过使用像 Flask 这样的服务器,甚至 标准库,构建您的应用程序?
But you know what's even simpler? Letting someone else do HTTP for you. Have you thought about using a server such as Flask, or even the standard library, to build your app?
这篇关于如何在一行中的套接字连接的发送方法中将字符串编码为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!