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'\xe4\xb8\x8d\xe7\x9f\xa5\xe9\x81\x93'
 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'

 

posted @ 2018-03-24 02:15  西康的博客  阅读(112)  评论(0编辑  收藏  举报