Conversion between str or bytes data and unicode characters

suggest change

The contents of files and network messages may represent encoded characters. They often need to be converted to unicode for proper display.

In Python 3, text is a str and binary data is bytes. A bytes literal uses a b prefix, as in b'' or b"". isinstance(b'abc', bytes) is True. Indexing a bytes object returns an int, not a one-byte string.

# You get from file or network "© abc" encoded in UTF-8

s = b'\xc2\xa9 abc' # bytes, not a str
s[0]                # 194, the integer value of the first byte
type(s)             # bytes

u = s.decode('utf-8')  # '© abc'
                       # bytes.decode converts bytes to str
u[0]                # '©', U+00A9 COPYRIGHT SIGN
type(u)             # str

u.encode('utf-8')   # b'\xc2\xa9 abc'
                    # str.encode produces bytes

Feedback about page:

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



Table Of Contents