考虑一下。
$ cat bla.py
u = unicode('d…')
s = u.encode('utf-8')
print s
$ python bla.py
File "bla.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file bla.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
如何在源代码中声明UTF-8字符串?
在源文件头,你可以声明。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
这在PEP 0263中有所描述。
那么你可以在字符串中使用UTF-8。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie wąż wąską dróżką'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
在Python 3中不需要这个声明,因为UTF-8是默认的源编码(见PEP 3120)。
此外,可能值得验证一下你的文本编辑器是否正确地用UTF-8编码了你的代码。否则,你可能有看不见的字符没有被解释为UTF-8。