[Tutor] send issue
Steven D'Aprano
steve at pearwood.info
Sat Mar 23 09:14:09 CET 2013
On 23/03/13 15:22, Lolo Lolo wrote:
>> You can use bytes() function:
>
>>>>> bytes('%d' % 3, 'utf-8')
>> b'3'
>
>> -m
>
> thanks this has solved everything. can i ask if this is an issue only in python 3 where sockets cant send strings? the docs state the argument is a string, but i believe that was for 2.7. I knew nothing about b'' or bytes() before today. thanks again
The thing to remember is that there are two types of strings:
byte strings
text strings (also known as Unicode)
In Python 2, strings created with "" are called "strings", and even though they are actually byte strings, Python tries really hard to pretend that they are text strings.
In Python 2, strings created with u"" are called "unicode strings". They are exactly the same as the strings you create in Python 3 using "" without the U.
In Python 3, strings created with b"" are called "bytes", for "byte strings", and Python no longer tries to pretend that they are text strings. (Python 2.7 also understands b"" syntax for creating byte strings.)
Summary:
* I want a series of bytes, e.g. for sending to a socket
- use "abc" or b"abc" in Python 2
- use b"abc" in Python 3
* I want a series of text characters:
- use u"abc" in Python 2
- use "abc" in Python 3
* I don't care what I get:
- use "abc" in Python 2 or 3, and so long as you don't
try to do anything too complicated, it will just work.
Does this help?
--
Steven
More information about the Tutor
mailing list