Decode () and encode ()

Source: Internet
Author: User

In Python, we use decode () and encode () to decode and encode


In Python, the Unicode type is used as the underlying type of the encoding. That


Decode encode


STR---------> Unicode--------->str


u = U ' China ' #显示指定unicode类型对象u

str = u.encode (' gb2312 ') #以gb2312编码对unicode对像进行编码

str1 = U.encode (' GBK ') #以gbk编码对unicode对像进行编码

str2 = U.encode (' utf-8 ') #以utf-8 encoding encodes Unicode pairs of images

u1 = Str.decode (' gb2312 ') #以gb2312编码对字符串str进行解码 to get Unicode

U2 = Str.decode (' utf-8 ') #如果以utf-8 encoding for STR decoding results, the original Unicode type cannot be restored

As in the above code, STR\STR1\STR2 are string types (str), which brings greater complexity to string manipulation.


The good news is, yes, that's python3. In the new version of Python3, the Unicode type is removed, instead it is a string type (str) that uses Unicode characters, and the string type (str) becomes the underlying type as shown below, and the encoded change to the byte type ( bytes) But the use of two functions does not change:


Decode encode


bytes------> str (Unicode)------>bytes


u = ' China ' #指定字符串类型对象u

str = u.encode (' gb2312 ') #以gb2312编码对u进行编码, Get bytes type Object str

u1 = Str.decode (' gb2312 ') #以gb2312编码对字符串str进行解码, gets the string type object u1

U2 = Str.decode (' utf-8 ') #如果以utf-8 encoding for STR decoding results, the original string content cannot be restored


This article is from the "Big Barren Sutra" blog, please be sure to keep this source http://2892931976.blog.51cto.com/5396534/1791406

Decode () and encode ()

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.