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

限于喜欢 提交于 2019-11-27 23:22:58

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

... 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')

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?

Use this:

s.send(b'your text')

Adding b in front of a string will convert it to bytes.

Putting a b or B before an opening quote will change a str literal to a bytes literal:

s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!