Code comment for Python #-*-Coding:utf-8-*-

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/arbel/article/details/7957782

If you want to write Chinese in the Python2 py file, you must add a line to declare the file encoded comments, otherwise python2 will use ASCII encoding by default.

[Python]View Plaincopy
    1. #-*-Coding:utf-8-*-

The question comes, why do you declare it?

First please refer to THE PEP http://www.python.org/dev/peps/pep-0263/of Python

The summary is as follows

1. The code note must be placed on the first or second line

2. The optional format is

[Python]View Plaincopy
    1. # coding=<encoding Name>

[Python]View Plaincopy
    1. #!/usr/bin/python
    2. #-*-Coding: <encoding name>-*-

[Python]View Plaincopy
    1. #!/usr/bin/python
    2. # Vim:set fileencoding=<encoding name>:


But looking down, it turns out that as long as the annotations have coding and corresponding codes,

[Python]View Plaincopy
    1. #!/usr/bin/python
    2. # Vim:set fileencoding=<encoding name>:


So it's been a bit confusing to have the most standard way of doing it.

Later thought, looked under the vim of the Python syntax highlighting file, the following regular expression is identified as the code declaration

[Plain]View Plaincopy
    1. \%^.*\ (\n.*\) \?#.*coding[:=]\s*[0-9a-za-z-_. \+.*$


For this regular is somewhat not understand, but the following must have coding:[code] or coding=[code], this should be considered as the standard way of declaring it.

But why is this usually the way it is?

[Python]View Plaincopy
    1. #-*-Coding:utf-8-*-


The answer is mentioned in PEP-0263, that is, Emacs and other editors use this way to encode the declaration.

There are a lot of things in Pep that are worth referencing, after all, you can tell why the program is designed like this.

Code comment for Python #-*-Coding:utf-8-*-

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.