Basics

suggest change

In Python 3, str stores Unicode text while bytes stores sequences of raw bytes.

type("f") is str          # True
type(b"f") is bytes      # True

Unicode to bytes

Unicode strings can be converted to bytes with .encode(encoding).

>>> "£13.55".encode('utf8')
b'\xc2\xa313.55'
>>> "£13.55".encode('utf16')
b'\xff\xfe\xa3\x001\x003\x00.\x005\x005\x00'

utf-16 writes a BOM and uses the platform byte order. The bytes above are little-endian.

If the encoding can’t handle the string, a UnicodeEncodeError is raised:

>>> "£13.55".encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xa3' in position 0: ordinal not in range(128)

Bytes to Unicode text

Bytes can be converted to Unicode strings with .decode(encoding).

The encoding used to decode the bytes must match the encoding that produced them.

>>> b'\xc2\xa313.55'.decode('utf8')
'£13.55'

If the bytes are not valid in that encoding, a UnicodeDecodeError is raised. The codec name in the message follows the platform byte order. The traceback path depends on the installation:

>>> b'\xc2\xa313.55'.decode('utf16')
# UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x35 in position 6: truncated data

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents