1. 程式人生 > >[Python]編碼宣告:是coding:utf-8還是coding=urf-8呢

[Python]編碼宣告:是coding:utf-8還是coding=urf-8呢

 

 

 

推薦:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

 

 

我們知道在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>

或者(使用流行編輯器中的格式化方式)

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

或者

  1.   #!/usr/bin/python
  2.   # 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
          ...

以上幾個例子充分說明了哪些是正確的寫法,哪些是正確的寫法