python37-encode与decode


编码(encode) 与 解码 ( decode )

str >>> (encode) >>> bytes
bytes >>> (decode) >>> str

str.encode():

>>> print('hello'.encode('utf-8'))
b'hello'
>>> print('中国'.encode('utf-8'))
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> print('dadada'.encode('utf-8'))
b'dadada'
>>> print('dadada'.encode()) #默认utf-8
b'dadada' >>> print('中国'.encode()) b'\xe4\xb8\xad\xe5\x9b\xbd'

bytes.decode():

>>> b = b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> b.decode() #默认utf-8
'中国'
>>> b.decode('utf-8')
'中国'