Re: [問題] 編碼問題
※ 引述《uranusjr (←這人是超級笨蛋)》之銘言:
: (中文的)Windows 版 Python shell 預設會用 Big5
: 0xACEC 是科的 Big5 編碼
: 當你在檔頭指定編碼時, 該檔案內的字串就會使用那個編碼
: 所以你 (1) 裡會是 0xE7A791, 這是科的 UTF-8 編碼
在檔頭的 coding 指示不會影響程式碼裡 str/unicode literal 的內容。
實際上程式碼裡出現的 "xxx" u"yyy" 在檔案內的數據到底是何編碼是由你使用
的 editor 決定,editor 使用哪種編碼就是哪種編碼,不會受檔頭的 coding
指示來影響。
檔頭的 coding 的作用是在於 Python parser/interpreter 如何處理 unicode
literal。
假如你使用的 editor 是使用 big5 編碼,而 Python runtime 預設編碼是 utf8,
那麼你在程式檔內有:
u"哈囉"
實際上 "" 內是 4 bytes("哈囉"二字以 big5 編碼後的數據),你得在檔頭註記
使用 big5 編碼,runtime 執行你的程式(或是編譯)才會正確處理該 literal。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.166.241.188
※ 編輯: sbrhsieh 來自: 118.166.241.188 (12/19 21:43)
→
12/19 23:20, , 1F
12/19 23:20, 1F
→
12/19 23:26, , 2F
12/19 23:26, 2F
→
12/20 23:55, , 3F
12/20 23:55, 3F
→
12/20 23:55, , 4F
12/20 23:55, 4F
→
12/21 01:17, , 5F
12/21 01:17, 5F
editor 產出 source file,檔案裡所有的文字都是使用特定的編碼,但因為所
使用的 keyword/identifier 都是英數字,這幾乎在每一種編碼裡的值都與 ASCII
相同,所以 editor 使用何種編碼影響都不大(除了有 BOM 的 encoding)。
但對於 str/unicode literal 內要使用非英數字元的情況下就需要注意。
在檔案中實際上界於 str/unicode literal 的兩個 " 中的 data 由 editor 使用
的 encoding 來決定(雖然在視覺上你在 editor 中看到的字元是一樣的在不同的
編碼下)。
在 compile 這樣的 expression 時:
u"..."
可以看成是在 compile-time/load-time 去 evaluate:
unicode("...", ENCODING, "strict")
而這個 ENCODING 可以由檔頭的 coding directive(註解)來變更。
※ 編輯: sbrhsieh 來自: 118.166.238.27 (12/21 01:31)
※ 編輯: sbrhsieh 來自: 118.166.238.27 (12/21 01:56)
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章