python 支持3種編碼聲明,通常經常使用能見到下面兩種python
1.# -*- coding: utf-8 -*-express
這種寫法是爲了兼容Emacs的編碼聲明vim
2.短一點,但Emacs不能用# coding=utf-8this
短一點,但Emacs不能用編碼
之因此要聲明未編碼類型 ,主要是中文出錯的問題。spa
在python 文件開頭(通常是第一行或第二行),用來講明你的Python源程序文件用使用的編碼。缺省狀況下你的程序須要使用ascii碼來寫,但若是在其中寫中文的話,python解釋器通常會報錯,但若是加上你所用的文件編碼,python就會自動處理再也不報錯。code
這裏要注意的是:orm
1.coding 後面使用 ":" 或 "=" 均可以utf-8
2.可是, ":" 或 "=" 必須和 coding之間沒有空格。以前我就試過有空格聲明失敗,仍是不支持中文。至於 ":" 或 "=" 後面,有沒有空格就沒所謂了。ci
見:https://www.python.org/dev/peps/pep-0263/
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.