模块中声明为utf8的Python unicode字符串文本

2024-06-16 11:07:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有utf-8头的dummie Python模块,如下所示:

# -*- coding: utf-8 -*-
a = "á"
print type(a), a

打印内容:

<type 'str'> á

但我认为,Python模块中声明为utf-8的所有字符串文本都会自动成为unicode类型,即str的intead类型。我是不是漏掉了什么,或者这是正确的行为?

为了获得作为unicode字符串的a,我使用:

a = u"á"

但这似乎不太“礼貌”,也不实际。有更好的选择吗?


Tags: 模块字符串文本声明类型内容typeunicode
3条回答

不,顶部的编解码器仅通知Python如何解释源代码,并使用该编解码器解释Unicode文本。它不会将文本bytestrings转换为unicode值。作为PEP 263状态:

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

如果Python的行为与您期望的一样,那么您也将无法对包含非ASCII字节值的bytestring值进行文本处理。

如果您的终端被配置为显示UTF-8值,那么打印UTF-8编码的字节字符串看起来是“正确的”,但这只是因为编码匹配的运气。

获取unicode值的正确方法是使用unicode文本或以其他方式生成unicode(从字节字符串解码、将整数码位转换为unicode字符等):

unicode_snowman = '\xe2\x98\x83'.decode('utf8')
unicode_snowman = unichr(0x2603)

在Python 3中,编解码器还适用于变量名的解释方式,因为您可以在名称中使用ASCII范围之外的字母和数字。Python 3中的默认编解码器是UTF-8,而Python 2中是ASCII。

不,这只是源代码编码。请看http://www.python.org/dev/peps/pep-0263/

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> :

这并不是说所有的文本都是unicode的,只是指出unicode文本应该如何解码。

应该使用unicode函数或u前缀将文字设置为unicode。

注意:在python3中,所有字符串都是unicode。

# -*- coding: utf-8 -*-

不会使字符串文本成为Unicode。举个例子,我有一个带有阿拉伯注释和字符串的文件,文件是utf-8:

# هذا تعليق عربي
print type('نص عربي')

如果我运行它,它将引发一个SyntaxError异常:

SyntaxError: Non-ASCII character '\xd9' in file file.py
on line 2, but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details

因此,为了实现这一点,我必须添加这一行来告诉解释器文件是UTF-8编码的:

# -*-coding: utf-8 -*-

# هذا تعليق عربي
print type('نص عربي')

现在它运行良好,但仍会打印<type 'str'>,除非我将字符串设置为Unicode:

# -*-coding: utf-8 -*-

# هذا تعليق عربي
print type(u'نص عربي')

相关问题 更多 >