需知:
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
上图仅适用于py2
1 #-*-coding:utf-8-*- 2 __author__ = 'Alex Li' 3 4 import sys 5 print(sys.getdefaultencoding()) 6 7 8 msg = "我爱北京天安门" 9 msg_gb2312 = msg.decode("utf-8").encode("gb2312") 10 gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk") 11 12 print(msg) 13 print(msg_gb2312) 14 print(gb2312_to_gbk) 15 16 in python2
1 #-*-coding:gb2312 -*- #这个也可以去掉 2 __author__ = 'Alex Li' 3 4 import sys 5 print(sys.getdefaultencoding()) 6 7 8 msg = "我爱北京天安门" 9 #msg_gb2312 = msg.decode("utf-8").encode("gb2312") 10 msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔 11 gb2312_to_unicode = msg_gb2312.decode("gb2312") 12 gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") 13 14 print(msg) 15 print(msg_gb2312) 16 print(gb2312_to_unicode) 17 print(gb2312_to_utf8) 18 19 in python3