python文件編碼說明 coding=utf-8


python 支持3種編碼聲明,一般常用能見到下面兩種

1.# -*- coding: utf-8 -*-

  這種寫法是為了兼容Emacs的編碼聲明

2.短一點,但Emacs不能用# coding=utf-8

短一點,但Emacs不能用

 

之所以要聲明未編碼類型 ,主要是中文出錯的問題。

在python 文件開頭(一般是第一行或第二行),用來說明你的Python源程序文件用使用的編碼。缺省情況下你的程序需要使用ascii碼來寫,但如果在其中寫中文的話,python解釋器一般會報錯,但如果加上你所用的文件編碼,python就會自動處理不再報錯。

這里要注意的是:

1.coding 后面使用 ":" 或 "=" 都可以

2.但是, ":" 或 "=" 必須和 coding之間沒有空格。之前我就試過有空格聲明失敗,還是不支持中文。至於 ":" 或 "=" 后面,有沒有空格就沒所謂了。

 

見:https://www.python.org/dev/peps/pep-0263/

Defining the Encoding

    Python will default to ASCII as standard encoding if no other
    encoding hints are given.

    To define a source code encoding, a magic comment must
    be placed into the source files either as first or second
    line in the file, such as:

          # coding=<encoding name>

    or (using formats recognized by popular editors)

          #!/usr/bin/python
          # -*- coding: <encoding name> -*-

    or

          #!/usr/bin/python
          # vim: set fileencoding=<encoding name> :

    More precisely, the first or second line must match the regular
    expression "coding[:=]\s*([-\w.]+)". The first group of this
    expression is then interpreted as encoding name. If the encoding
    is unknown to Python, an error is raised during compilation. There
    must not be any Python statement on the line that contains the
    encoding declaration.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM