Understanding about python character encoding

Source: Internet
Author: User

Python is used because of its beauty;
The following describes the application of common character encoding in python:
S = "China"
Print repr (s) # The Original output characters are expressed in hexadecimal notation.
# '\ Xd6 \ xd0 \ xb9 \ xfaa'
# We are most familiar with Ansi strings. English occupies one byte and Chinese characters are two bytes. They end with one \ 0 and are often used in txt text files.
# Unicode string. Each character (Chinese character or English letter) occupies 2 bytes and ends with 2 consecutive \ 0 characters.
# UTF-8: 1 byte in English and 3 bytes in Chinese
S1 = s. decode ('gbk') // The base64-encoded data must be decoded.
# U' \ u4e2d \ u56fda'
S2 = s1.encode ('utf-8') // encode unicode characters in UTF-8 format
# '\ Xe4 \ xb8 \ xad \ xe5 \ x9b \ xhangzhou'
S3 = s2.decode ('utf-8') // since it is encoded in UTF-8 format, it must be decoded in UTF-8 format.
# U' \ u4e2d \ u56fda'
S4 = s3.encode ('gbk') // The final part is encoded into common Chinese encoding formats.
# '\ Xd6 \ xd0 \ xb9 \ xfaa'

# Actually, it's just an expression.
Print s. decode ('gbk'). encode ('utf-8'). decode ('utf-8'). encode ('gbk ')
# China

Therefore, the character encoding method in python is actually very simple, but sometimes it is always wrong, hey
Now, let's make the above summary. I hope you will keep it in mind and never make similar mistakes.

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.