python 字符编码

首先需要注意的是python2的默认编码是ascii,python3默认是utf8

任何字符的转码都要先转到unicode后再转成其他编码。

encode 编码

decode 解码

 1 In [1]: str1 = '不知道'
 2 
 3 In [2]: str1
 4 Out[2]: '不知道'
 5 
 6 In [3]: str1.encode('utf8')  # 使用utf8编码
 7 Out[3]: b'xe4xb8x8dxe7x9fxa5xe9x81x93'
 8 
 9 In [4]: str2 = str1.encode('utf8') # 使用utf8编码
10 
11 In [5]: str2.decode('utf8') #使用utf8解码
12 Out[5]: '不知道'
13 
14 In [6]: a = b'test'
15 
16 In [7]: a
17 Out[7]: b'test'
18 
19 In [8]: a.decode('utf8')
20 Out[8]: 'test'
原文地址:https://www.cnblogs.com/qikang/p/8630419.html