30-07-2009 o 12:29:24 Francesco Bochicchio said:
Try putting a 'b' before the constant string that you want to send:
<class 'bytes'>
It's true. In python '...' literals are for strings ('str' type) and
b'...' literals are for binary data (bytes type).
Sockets' send() and recv() need binary data ('bytes' objects).
or use something like this to convert non constant strings (with only
ASCII characters) into bytes:
<class 'str'>
What???
'str' type in Python 3.x IS NOT a type of "non-constant" strings and
IS NOT a type of strings "with only ASCII characters"!
'str' type in Python 3.x *is* the type of immutable ('constant') and
Unicode character (Unicode, not only ASCII) strings. It's the same what
'unicode' type in Python 2.x.
'bytes' type objects in Python 3.x are also immutable. They are good
for binary data (also text data encoded to binary data; see below).
'bytearray' type objects are like 'bytes', but mutable (like e. g.
lists).
b'A non-constant string : 12 '
You could also use struct.pack , that in python 3.x returns bytes and
not strings. In this case you need to specify the size of the string
(extra bytes are zero-filled):
import struct
What for all that weird actions???
* Simply do:
bytes_object = str_object.encode(<encoding>)
or
bytes_object = bytes(str_object, <encoding>)
-- where <encoding> could be e.g. 'ascii', 'utf-8', 'iso-8859-1' etc.;
using the former method, you can omit this argument -> then default
encoding will be used (usualy 'utf-8').
* As easily as that, you can convert bytes to str:
str_object = bytes_object.decode(<encoding>)
or
str_object = str(bytes_object, <encoding>)
* Some examples:
Traceback (most recent call last):
b'What makes you think she is a witch?'
"b'What makes you think she is a witch?'"
[^ note this]
Cheers,
*j