7

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?

3
  • 1
    You could have combined the string literal with the str.encode() call too, you know: s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('ascii')). Not that you need to, what with b'...' byte literals. Commented Jan 29, 2016 at 19:15
  • @MartijnPieters I had tried s.send('mystring').encode('utf-8') so the encode was in the wrong place. Commented Jan 29, 2016 at 19:17
  • 3
    Because that tries to call .encode() on the return value of s.send(). Look closely at the parentheses; message.encode() is entirely contained inside s.send(). So is my version with s.send('....'.encode('utf8')). Commented Jan 29, 2016 at 19:18

3 Answers 3

10

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?

Sign up to request clarification or add additional context in comments.

Comments

3

Use this:

s.send(b'your text')

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

Comments

2

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

3 Comments

Is there a difference between b and B?
@Holloway: Yes, one usually requires the shift key to type, and the other doesn't.
@jwodder bUT WHAT IF i HAVE A BROKEN cAPS lOCK KEY?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.