Python 編碼問題

  • 4211
  • 0

Python 編碼問題

在 Python 2.X  中,字串值只有兩個型態:(1) byte string 與 (2) unicode string。

 

byte string 在程式碼中,是使用單引號「 ’」來包夾內容,例如:’Hello World’、’測試’等。

PS.  你可以透過「Control Panel」-> 「Region and Language」->「Administrative」->「Current language for non-Unicode programs:」來檢視系統目前的 Locale:

image

 

或是在 Command line 下,輸入 systeminfo.exe  來進行檢視:

image

 

由於系統 Locale 是 zh-tw 也就是 Big5 編碼,CPython 在使用 byte string 的時候,會根據電腦的系統 Locale 來轉換輸出的字元。所以在 command line 下面,還是可以正常顯示中文:

image

 

unicode string 在程式碼中,除了也是使用單引號「 ’」來包夾內容,前面還多了 u 的字元來表示 unicode:例如:u’Hello World’、u’測試’等。

基本上 unicode 的世界非常的美好,CPython 可以正常無誤顯示中文。

image

 

在 Python3.X 的世界裡,為了解決編碼的問題,所有的 string 都是 unicode string,特別使用 u 來表示,反而會出錯!

image

但是搞不好 Python3.3 又可以使用 u 也說不定:PEP 414 -- Explicit Unicode Literal for Python 3.3

 

而在 PyScripter 開發環境下,原始碼預設是用 ANSI 來進行編碼,所以在處理中文字上面可能會出現問題。

就如同 notepad 一樣:

image

PyScipter:

Image(2)

 

因為,PyScripter 預設檔案都是 ANSI 編碼,你可以透過以下兩種方法進行調整:

1. 針對單一檔案進調整:

Edit –> File Format –> UTF-8

Image(3)

這個方式僅限於單一檔案,每次新增檔案都要手動調整。

 

2. 更改 PyScipter 檔案格式預設值:

(1) Tools –> Optins –> IDE Options…

Image(4)

(2) Default file encoding for new files:選擇 sf_UTF8

Image(5)

 

不過,根據 PEP 0263 -- Defining Python Source Code Encodings 的建議,最好還是在原始碼加上「# -*- coding: utf-8 -*-」來讓編輯器識別。

Image(6)

 

參考文章:

PEP 3120 -- Using UTF-8 as the default source encoding

PEP 0263 -- Defining Python Source Code Encodings

PEP 414 -- Explicit Unicode Literal for Python 3.3