版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35212491/article/details/81321376
编码和解码流程图
由
unicode
编码转换成utf-8
或gbk
的过程叫做编码,将utf-8
还原成unicode
的过程叫做解码。
Python3
# python3
In [1]: s1 = "你好,中文"
In [2]: s1
Out[2]: '你好,中文'
In [3]: s2 = s1.encode("utf-8")
In [4]: s2
Out[4]: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\xad\xe6\x96\x87'
In [5]: s3 = s2.decode("utf-8")
In [6]: s3
Out[6]: '你好,中文'
Python3 中,文本字符串类型 (
unicode
) 被命名为str
,字节字符串类型被命名为bytes,python3
默认是unicode
编码,如果想得到bytes
类型,可以在字符串前加上前缀b,或者encode
一下。
>>> string = "你好,中文"
>>> type(string)
<class 'str'>
>>>
>>> s2 = b'hello'
>>> type(s2)
<class 'bytes'>
>>>
>>> string.encode('utf-8')
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\xad\xe6\x96\x87'
>>>
str
对象有一个encode()
方法,bytes
对象有一个decode()
方法
Python2
>>> s1 = '中文'
>>> s1
>>>'\xe4\xb8\xad\xe6\x96\x87'
>>> type(s1)
<type 'str'>
>>> s2 = s1.decode('utf-8')
>>> s2
u'\u4e2d\u6587'
>>> type(s2)
<type 'unicode'>
>>> s3 = s2.encode('utf-8')
>>> s3
'\xe4\xb8\xad\xe6\x96\x87'
>>> type(s3)
<type 'str'>
>>> type(b'hello')
<type 'str'>
Python3 与 Python2 的区别
python3 中的 str 在python2中叫 unicode, bytes 对象对应 python2 中的 str 对象。python2中str对象有一个 encode 方法,文本字符对象(unicode)有一个decode方法。
unicode.decode()
>>> a = u'中文'
>>> a.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>>
unicode.decode()
实际执行过程为unicode.encode('ascii').decode('utf-8')
str.encode()
>>> b = '中文'
>>> b.encode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>>
str.encode()
实际执行过程为str.decode('ascii').encode('utf-8')
可以通过设置默认编码来减少错误
import sys
reload(sys)
# 需要 reload sys 模块后才会有 setdefaultencoding 方法
sys.setdefaultencoding('utf-8')