简介
编码方式:ASCII码、GB2312、GB18030、万国码Unicode。其中
Unicode》1字符=2字节=16位;
ASCII》1字符=1字节=8位;
为解决提升后的英文字符的多空间占用问题,将Unicode扩展集为utf-8,是一种可变长的字符编码,默认所有英文字符按ASCII的1字节形式存储,所有的中文字符按3字节处理。为什么utf8占用3个字节?
Python3.5中的转换
s = "你好"
s_gbk = s.encode("gbk")
print('s_gbk',s_gbk)
print('defult',s.encode())
gbk_utf = s_gbk.decode('gbk').encode('utf-8')
print('gbk_utf',gbk_utf)
print('str:',gbk_utf.decode('utf-8'))
print('s_gbk.decode',s_gbk.decode('gbk'))
s_gbk b’\xc4\xe3\xba\xc3’
defult b’\xe4\xbd\xa0\xe5\xa5\xbd’
gbk_utf b’\xe4\xbd\xa0\xe5\xa5\xbd’
str: 你好
s_gbk.decode 你好
Python2.7中的转换
#-*-coding:utf-8-*-
import sys
print(sys.getdefaultencoding())
msg = "我爱北京天安门"
msg_gb2312 = msg.decode("utf-8").encode("gb2312")
gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk")
print(msg)
print(msg_gb2312)
print(gb2312_to_gbk)
参考
【1】详细文章http://www.cnblogs.com/yuanchenqi/articles/5956943.html
http://www.diveintopython3.net/strings.html
【2】6. 字符编码与转码http://www.cnblogs.com/alex3714/articles/5717620.html