Joni
(Joni)
December 16, 2024, 3:25pm
1
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 ?
abessman
(Alexander Bessman)
December 16, 2024, 3:29pm
2
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.'
Joni
(Joni)
December 16, 2024, 3:33pm
3
I tried
message = b'This is the message. It will be repeated.'
It works.
franklinvp
(Franklinvp)
December 16, 2024, 5:14pm
5
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
tjreedy
(Terry Jan Reedy)
December 20, 2024, 5:48pm
6
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)`.