struct.unpack: why 's' fmt char convert to bytestring

MRAB python at mrabarnett.plus.com
Thu May 15 10:47:58 EDT 2014


On 2014-05-15 13:34, GuoChao wrote:
> T <https://docs.python.org/2.7/library/struct.html>he Python
> documentation gives this same example:
>
>>>>record  =  b'raymond\x32\x12\x08\x01\x08'
>>>>name,  serialnum,  school,  gradelevel  =  unpack('<10sHHb',  record)
>
> but get different results as to 's', don't know why this change in
> Python 3?  need extra work to encode...
>
>>>>name
>>>>'raymond   '  #for  2.7  <https://docs.python.org/2.7/library/struct.html>
>
>>>>name
>>>>b'raymond   '  #for  _3.3  <https://docs.python.org/3.3/library/struct.html>_
>
They are actually the same result; they are both bytestrings (a string
of bytes).

In Python 2, the 'str' class is for bytestrings and the 'unicode' class
is for Unicode strings, so 'abc' (or b'abc') is a bytestring and u'abc'
is a Unicode string.

In Python 3, the 'bytes' class is for bytestrings and the 'str' class
is for Unicode strings, so b'abc' is a bytestring and 'abc' is a
Unicode string.




More information about the Python-list mailing list