在 Python 源代码中使用 UTF-8 编码 [英] Working with UTF-8 encoding in Python source
本文介绍了在 Python 源代码中使用 UTF-8 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
$ 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 字符串?
How can I declare UTF-8 strings in source code?
推荐答案
在源头中你可以声明:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
它在 PEP 0263 中有描述:
然后你可以在字符串中使用 UTF-8:
Then you can use UTF-8 in strings:
#!/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).
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
此外,验证您的文本编辑器是否以 UTF-8 正确编码您的代码可能是值得的.否则,您可能会有不被解释为 UTF-8 的不可见字符.
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
这篇关于在 Python 源代码中使用 UTF-8 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文