对于中文用户,特别需要关注Python的编码技术. 列举一些常用的技巧。
- 代码中的编码设置,应该在代码最初两行内包含:
# -*- coding: gb18030 -*-
- 获得/设置系统的缺省编码
sys.getdefaultencoding()
sys.setdefaultencoding('utf-8') - 获得文件系统的文件名的编码
sys.getfilesystemencoding()
- 获得当前终端的输入、输出编码
sys.stdout.encoding
sys.stdin.encoding - 编码转换(先转换为unicode,再转换为具体的编码),有两种方法:
unicode('abc', 'mbcs').encode('utf-8')
'abc'.decode('mbcs').encode('utf-8')
其他参考:
python and unicode原文地址:
http://czug.org/blog/panjy/python-encoding/blogentry_view?month:int=1&year:int=2007