一些来自下载代码的源文件具有以下标头
# -*- coding: utf-8 -*-
我知道什么是utf-8编码,但是为什么要把它作为python源文件的头文件呢?
发布于 2012-12-11 03:30:41
在需要在代码中使用非ascii字符的地方,例如:
ă
翻译员会抱怨他不理解那个字符。
通常在定义常量时会发生这种情况。
示例:添加到x.py
print 'ă'
然后启动python控制台
import x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "x.py", line 1
SyntaxError: Non-ASCII character '\xc4' in file x.py on line 1,
but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details
发布于 2012-12-11 04:38:00
始终使用UTF-8,并确保您的编辑器也使用UTF-8。如果使用Python 27,请像这样启动Python脚本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
这是Nick Johnson关于Python和UTF-8的一篇很好的博客文章:
http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python顺便说一句,这篇文章是在他可以使用之前写的:
from __future__ import unicode_literals
发布于 2012-12-11 03:32:54
当您使用非ascii字符时。例如,当我用挪威语注释我的源码时,如果在.py中出现了charachters,它就会报错,而不是“编译”。
https://stackoverflow.com/questions/13807748
复制相似问题