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')
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'
Should I not be using send?
str
, the type of text, is not the same asbytes
, the type of sequences of eight-bit words. To concisely convert from one to the other, you could inline the call toencode
(just as you could with any function call)..... bearing in mind that it's often a good idea to specify the encoding you want to use...
... but it's simpler to use a bytes literal. Prefix your string with a
b
: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?
Putting a
b
orB
before an opening quote will change astr
literal to abytes
literal:Use this:
Adding
b
in front of a string will convert it tobytes
.