Python解码和编码

decode是解码,encode时编码

 

在Python2中默认时ASCLL,在Python3中默认时Unicode

 

 

gbk转向utf-8:先将gbk解码成Unicode,在编码成utf-8。

utf-8转向gbk:先将utf-8解码成Unicode,在编码成gbk。

 

 

Python2代码:

 1 #-*- coding:utf-8 -*-
 2 
 3 '''
 4 @auther: Starry
 5 @file: py2ende.py 
 6 @time: 18-1-12 下午9:52 
 7 '''
 8 
 9 '''
10 Python2中默认是ASCII
11 '''
12 import sys
13 
14 print(sys.getdefaultencoding())
15 
16 s = '你好'
17 
18 s_unicode = s.decode('utf-8')
19 s_gbk = s_unicode.encode('gbk')
20 
21 print(s_unicode)
22 print(s_gbk)
23 
24 gbk_to_utf8 = s_gbk.decode('gbk').encode('utf-8')
25 print(gbk_to_utf8)

 

 

Python3代码:

 1 #!/usr/bin python3.5
 2 #-*- coding:utf-8 -*-
 3 
 4 '''
 5 @auther: Starry
 6 @file: py3ende.py 
 7 @time: 18-1-12 下午9:56 
 8 '''
 9 
10 '''
11 Python3中默认时Unicode
12 '''
13 
14 import sys
15 print(sys.getdefaultencoding())
16 
17 
18 s = '你好'
19 print(s)
20 
21 
22 s_utf8 = s.encode('utf-8')
23 s_gbk = s.encode('gbk')
24 
25 print(s_utf8)
26 print(s_gbk)
27 
28 gbk_unicode = s_gbk.decode('gbk')
29 print(gbk_unicode)
30 
31 utf8_to_gbk = s_utf8.decode('utf-8').encode('gbk')
32 gbk_to_utf8 = s_gbk.decode('gbk').encode('utf-8')
33 
34 print(utf8_to_gbk)
35 print(gbk_to_utf8)

 

posted @ 2018-01-12 22:10  starry_sky  阅读(403)  评论(0编辑  收藏  举报