String conversion

I am sorry. This is too basic.

In the following lines of code.

message = 'This is the message.  It will be repeated.'
print(sys.stderr, 'sending "%s"' % message)
sock.sendall(message)

I got the following error.

sock.sendall(message)
TypeError: a bytes-like object is required, not 'str'

Q: how to convert “message” into string ?

It is a string. You don’t want a string. You want a bytes-like object. You can make message into bytes by prepending the string with b:

message = b'This is the message.  It will be repeated.'

I tried

message = b'This is the message.  It will be repeated.'

It works.

And it you don’t want, or cannot modify the given str, you can use str.encode to give you the bytes message.encode().

3 Likes

Printing str(sys.stderr)' makes no sense in the context of your question. If you want to print to stderr, this should be print(‘sending “%s”’ % message, file=sys.stderr)`.