快速理解python2中的编码问题

 1 # -*- coding:utf-8 -*-
 2 
 3 
 4 
 5 '''
 6 python2 中的字符编码有str和unicode(字符串类型的名字)
 7 str类型字符串类型在内存中存储的是bytes数据
 8 Unicode类型字符串在内存中存储的是unicode数据
 9 两种数据之间是什么关系?
10 解码(encode)和编码(decode)
11 
12 unicode转换为bytes数据的过程是编码
13 bytes数据转换为unicode数据的过程是解码
14 
15 '''
16 name = "小沫"
17 name2 = u"小沫"
18 print type(name) # <type 'str'>
19 print repr(name) # '\xe5\xb0\x8f\xe6\xb2\xab'
20 print type(name2) # <type 'unicode'>
21 print repr(name2) # u'\u5c0f\u6cab'
22 
23 name3 = name.decode('utf-8')
24 print type(name3) # <type 'unicode'>
25 print repr(name3) # u'\u5c0f\u6cab'
26 
27 name4 = name2.encode('utf-8')
28 print type(name4) # <type 'str'>
29 print repr(name4) # '\xe5\xb0\x8f\xe6\xb2\xab'

猜你喜欢

转载自www.cnblogs.com/xm17/p/9710759.html
今日推荐