需知: 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
Python2中的编码转换:
1 #python2 2 import sys 3 print(sys.getdefaultencoding()) 4 5 6 msg = "我爱北京天安门" 7 msg_gb2312 = msg.decode("utf-8").encode("gb2312") 8 gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk") 9 10 print(msg) 11 print(msg_gb2312) 12 print(gb2312_to_gbk)
1 #-*-coding:gb2312 -*- 2 import sys 3 print(sys.getdefaultencoding()) 4 5 6 msg = "我爱北京天安门" 7 #msg_gb2312 = msg.decode("utf-8").encode("gb2312") 8 msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔 9 gb2312_to_unicode = msg_gb2312.decode("gb2312") 10 gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") 11 12 print(msg) 13 print(msg_gb2312) 14 print(gb2312_to_unicode) 15 print(gb2312_to_utf8)
原文:https://www.cnblogs.com/bocaimao/p/10340109.html