作者sbrhsieh (偶尔想摆烂一下)
看板Python
标题Re: [问题] 编码问题
时间Sun Dec 19 21:42:09 2010
※ 引述《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)
1F:→ shihyuyao:editor 是什麽编码是指说我存档时候选择的档案编码吗? 12/19 23:20
2F:→ sbrhsieh:这是一种方式。不同 editor 的做法不同。 12/19 23:26
3F:→ shihyuyao:有个疑问editor 是使用 big5 编码那u"哈罗"还是big5编译 12/20 23:55
4F:→ shihyuyao:那加上 u还有什麽作用吗? 12/20 23:55
5F:→ sbrhsieh:有 leading u 是 unicode literal。 12/21 01:17
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)