1. character encoding
#ASCII码里只能存英文和特殊字符 cannot be saved in English 1 bytes 8 bits
#中文编码为GBK operating system encoding is also GBK
#为了统一存储中文和英文和其他语言文字出现了万国码Unicode all one character takes 2 bytes 16 bits
#英文文档改为Unicode编码大小变大一倍 to solve this wasted space problem
#出现了Unicode扩展集 Utf-8 for variable-length character encoding default English characters stored in ASCII code in Chinese by 3 bytes
Encoding must first decode into Unicode and then transcoding to target code
#获取默认编码
Import sys
Print (sys.getdefaultencoding ())
#文件头声明编码
#-*-coding:gbk-*-
#文件转码都要先转换成Unicode再转换成目标编码
#转换成Unicode时需要decode ("self-coding") and pass in self-encoding to convert to Unicode
#再转换成目标编码时 to encode ("target Encoding")
#ptyon3里 encode not only converted the code, it became bits.
s= "hello"
#转换成gbk编码
S_gbk=s.encode ("gbk")
Print (s_gbk)
#gbk转换成utf-8
S_utf8=s_gbk.decode ("gbk"). encode ("utf-8")
Print (s_utf8)
#utf-8 to gb2312
S_gb2312=s.encode ("gb2312")
Print (s_gb2312)
#gb2312转换为gbk
S_gbk2=s_gb2312.decode ("gb2312"). encode ("gbk")
Print (s_gbk2)
#gb2312转换为utf-8
S_utf8_2=s_gb2312.decode ("gb2312"). encode ()
Print (s_utf8_2)
Print (s.encode ("utf-8"). decode ("utf-8"). encode ("gb2312"). decode ("gb2312"))
#gbk向下兼容gb2312和gb23180
Python Learning Day2 notes (character Encoding)