Python Learning Day2 notes (character Encoding)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.