Created
April 16, 2014 19:32
-
-
Save guori12321/10924016 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
最通用的做法是,在程序的前面加上 | |
# -*- coding: utf-8 -*- | |
import sys | |
reload(sys) # reload 才能调用 setdefaultencoding 方法 | |
sys.setdefaultencoding('utf-8') # 设置 'utf-8' | |
第一行注释是程序本身的编码,就是说在代码中如果有汉字的字条串,一样可以识别。下面的几行,是使程序内部使用utf-8编码。这样,读写文件,和在mac的终端中重定向输出都没问题。 | |
如果没有后三行,在处理utf-8字条串时,要用 | |
print str.encode('utf-8') | |
encode和decode的区别: | |
因为 Python 认为 16 位的 unicode 才是字符的唯一内码,而大家常用的字符集如 gb2312,gb18030/gbk,utf-8,以及 ascii 都是字符的二进制(字节)编码形式。把字符从 unicode 转换成二进制编码,当然是要 encode。 | |
反过来,在 Python 中出现的 str 都是用字符集编码的 ansi 字符串。Python 本身并不知道 str 的编码,需要由开发者指定正确的字符集 decode。 | |
具体参考 http://in355hz.iteye.com/blog/1860787 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment