Python 2.7 Learning Notes Chinese processing

Source: Internet
Author: User

First, when we write a Python code file, the file itself takes an encoding format, such as Utf-8 or GBK

At this point we need to set the encoding format of the file at the beginning of the Python file to tell the compiler.

If the encoding format of the file is Utf-8, the first line of the file needs to add the following statement

#coding =utf-8

If the encoding format of the file is Utf-8, the first line of the file needs to add the following statement

#coding =GBK

If the format is set to Utf-8, the Linux execution, the Chinese processing, including the display does not have any problems.

However, if the format is set to Utf-8, under window, when executed under the command line, it is found that printing Chinese with print is garbled.

The reason is because, although the file is declared as Utf-8, the source file is saved with Utf-8 encoding. But the local default encoding for Windows (www.111cn.net) is cp936, which is GBK encoding, so printing utf-8 strings directly in the console is garbled. Note that, in fact, only display problems, warehousing and other processing is not a problem.

There are two kinds of solutions.

I. Programme I:

To change the encoding format of the file to GBK, and to change the first line of the file to #coding=gbk, then there is no problem with Chinese.

But the problem with this scenario is that if the file is placed under Linux it may show a problem. Because there is no GBK character set under the General Linux machine.

II. Programme II

The file is still encoded with Utf-8, and the first line of the file header is still #coding=utf-8

At this point in print Chinese need to encode, code such as:

Print "Chinese". Decode (' Utf-8 '). Encode (sys.getfilesystemencoding ())

Note: Because the SYS module is used, you need to add the import sys in the statement execution

As a result of this problem, the print statement is bloated and can be considered in its own package.

  

Python 2.7 Learning Notes Chinese processing

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.