[Tutor] UDP client
Peter Otten
__peter__ at web.de
Sun Feb 26 04:41:30 EST 2017
Phil wrote:
> On 26/02/17 18:42, Alan Gauld via Tutor wrote:
>> On 26/02/17 06:44, Phil wrote:
>>
>>> s.connect((host, 1210))
>>> data = "GET_LIST"
>>
>> This is a string, you need to use bytes.
>>
>> data = bytes("GET_LIST",'utf8')
>>
>
> Thank you Peter and Alan for your response.
>
> Converting "data" to bytes worked, of course. Now I have to, I think, do
> the opposite to the received data.
>
> while 1:
> buf = s.recv(2048)
> if not len(buf):
> break
> print("Received: %s" % buf)
>
> This prints the correct result like this:
>
> b'ABC\DEF\ETC\n' n/
>
> Instead of:
>
> ABC
> DEF
> ETC
>
> I tried str.decode(buf) but doesn't seem to be the answer.
Try
buf.decode("utf-8")
Generally:
bytes --> unicode:
some_str = some_bytes.decode(encoding)
some_str = str(some_bytes, encoding)
unicode --> bytes:
some_bytes = some_str.encode(encoding)
some_bytes = bytes(some_str, encoding)
I always use encode/decode, probably because bytes is an alias of str in py2
and does not accept a second argument.
More information about the Tutor
mailing list