我們知道在Python源碼的頭文件中要聲明編碼方式,如果你不只是會用到ascii碼,很多人都寫得都有點差別:
#coding=utf-8
#coding:utf-8
#-*- coding:utf-8 -*-
那麼怎樣寫纔是有效地呢,哪些優勢無效的呢?
可以查看下http://www.python.org/dev/peps/pep-0263/的解釋
粗略的看下:
概要:
這個PEP的目的是介紹在一個Python源文件中如何聲明編碼的語法。隨後Python解釋器會在解釋文件的時候用到這些編碼信息。最顯著的是源文件中對Unicode的解釋,使得在一個能識別Unicode的編輯器中使用如FUT-8編碼成爲可能
怎麼聲明呢?
如果在Python中我們並沒有聲明別的編碼方式,就是以ASCII編碼作爲標準編碼方式的
爲了定義源文件的編碼方式,一個魔法是的聲明應當被放在這個文件的第一行或者是第二行例如:
#coding=<encoding name>
或者(使用流行編輯器中的格式化方式)
#!/usr/bin/python
# -*- coding: <encoding name> -*-
或者
#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
不管怎麼樣,這些在第一行或者第二行的聲明都要符合正則表達式
"coding[:=]\s*([-\w.]+)"
所以我們就可以知道爲什麼使用冒號或者等號都可以了,如果聲明的編碼python不能識別就會報錯
Examples
These are some examples to clarify the different styles for
defining the source code encoding at the top of a Python source
file:
1. With interpreter binary and using Emacs style file encoding
comment:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys
...
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import os, sys
...
#!/usr/bin/python
# -*- coding: ascii -*-
import os, sys
...
2. Without interpreter line, using plain text:
# This Python file uses the following encoding: utf-8
import os, sys
...
3. Text editors might have different ways of defining the file's
encoding, e.g.
#!/usr/local/bin/python
# coding: latin-1
import os, sys
...
4. Without encoding comment, Python's parser will assume ASCII
text:
#!/usr/local/bin/python
import os, sys
...
5. Encoding comments which don't work:
Missing "coding:" prefix:
#!/usr/local/bin/python
# latin-1
import os, sys
...
Encoding comment not on line 1 or 2:
#!/usr/local/bin/python
#
# -*- coding: latin-1 -*-
import os, sys
...
Unsupported encoding:
#!/usr/local/bin/python
# -*- coding: utf-42 -*-
import os, sys
...
以上幾個例子充分說明了哪些是正確的寫法,哪些是正確的寫法
#!/usr/bin/env python
#-*- coding: utf-8 -*-
第一行註釋事爲了告訴Linux/OS X系統,這是一個Python可執行程序,Windows系統會忽略這個註釋;
第二行註釋市爲了告訴Python解釋器,按照UTF-8編碼讀取源代碼,否則,在源代碼中寫的中文輸出可能會有亂碼。
原文:https://blog.csdn.net/zhongbeida_xue/article/details/81736671