This PEP proposes to introduce a syntax to declare the encoding of
a Python source file. The encoding information is then used by the
Python parser to interpret the file using the given encoding. Most
notably this enhances the interpretation of Unicode literals in
the source code and makes it possible to write Unicode literals
using e.g. UTF-8 directly in an Unicode aware editor.
强调我的。
如果没有编解码器声明,Python就不知道如何解释非ASCII字符:
$ cat /tmp/test.py
example = '☃'
$ python2.7 /tmp/test.py
File "/tmp/test.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file /tmp/test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python
# -*- coding: <encoding name> -*-
or
#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
不,顶部的编解码器仅通知Python如何解释源代码,并使用该编解码器解释Unicode文本。它不会将文本bytestrings转换为unicode值。作为PEP 263状态:
强调我的。
如果没有编解码器声明,Python就不知道如何解释非ASCII字符:
如果Python的行为与您期望的一样,那么您也将无法对包含非ASCII字节值的bytestring值进行文本处理。
如果您的终端被配置为显示UTF-8值,那么打印UTF-8编码的字节字符串看起来是“正确的”,但这只是因为编码匹配的运气。
获取unicode值的正确方法是使用unicode文本或以其他方式生成unicode(从字节字符串解码、将整数码位转换为unicode字符等):
在Python 3中,编解码器还适用于变量名的解释方式,因为您可以在名称中使用ASCII范围之外的字母和数字。Python 3中的默认编解码器是UTF-8,而Python 2中是ASCII。
不,这只是源代码编码。请看http://www.python.org/dev/peps/pep-0263/
这并不是说所有的文本都是unicode的,只是指出unicode文本应该如何解码。
应该使用
unicode
函数或u
前缀将文字设置为unicode。注意:在python3中,所有字符串都是unicode。
不会使字符串文本成为Unicode。举个例子,我有一个带有阿拉伯注释和字符串的文件,文件是utf-8:
如果我运行它,它将引发一个
SyntaxError
异常:因此,为了实现这一点,我必须添加这一行来告诉解释器文件是UTF-8编码的:
现在它运行良好,但仍会打印
<type 'str'>
,除非我将字符串设置为Unicode:相关问题 更多 >
编程相关推荐