通常,我们新创建的py文件,是以标准的7位ASCII码存储,而这种文件格式是不支持unicode字符的。因此,默认新建一个py文件,代码中含有中文(包括注释),则会报错。
name = "好心情"
print name
SyntaxError: Non-ASCII character '\xe4' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
print name
SyntaxError: Non-ASCII character '\xe4' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
解决这个问题通常有两种方法:
1. 通过编辑器修改文件编码格式
2. 在文件开始行,声明py格式
通常采用方式二,可以安全可靠的保证程序正常运行。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name = "好心情"
print name
好心情
# -*- coding: utf-8 -*-
name = "好心情"
print name
好心情
除了py代码中存在中文的问题,其实还有一个中文问题,即程序在做编码、解码时,unicode也会报错。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name = "好心情"
print name.encode('gbk')
Traceback (most recent call last):
File "test.py", line 4, in <module>
print a.encode('gbk')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
# -*- coding: utf-8 -*-
name = "好心情"
print name.encode('gbk')
Traceback (most recent call last):
File "test.py", line 4, in <module>
print a.encode('gbk')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
这是因为python2.x中在处理中文时,默认编码defaultencoding是ascii,name.encode('gbk')就相当于name.decode('ascii').encode('gbk'),由于无法转换为ascii,因此报错。
有两种办法可以解决此问题:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name = "好心情"
#一种是转换时指定转码方式
print name.decode('utf-8').encode('gbk')
#另一种是修改系统默认转码方式
import os
reload(sys)
sys.setdefaultencoding('utf8')
print name.encode('gbk')
# -*- coding: utf-8 -*-
name = "好心情"
#一种是转换时指定转码方式
print name.decode('utf-8').encode('gbk')
#另一种是修改系统默认转码方式
import os
reload(sys)
sys.setdefaultencoding('utf8')
print name.encode('gbk')
这里总结一下关于defaultencoding的知识点:
1. s.encode("utf-8") 等价于 s.decode(defaultencoding).encode("utf-8")
2. 调用setdefaultencoding时必须要先reload一次sys模块,因为setdefaultencoding函数在被系统调用后被删除。
Leave a Reply