在Python2.6中有没有使用unicode字符的问题?

2024-06-25 22:49:56 发布

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

我们已经在Python2.6下运行了代码库。为了准备Python3.0,我们已经开始添加:

from __future__ import unicode_literals

进入我们的.py文件(当我们修改它们时)。我想知道是否有其他人一直在这样做,并遇到了任何不明显的问题(可能在花了大量时间调试之后)。


Tags: 文件代码frompyimport时间unicodefuture
3条回答

我在使用unicode字符串时遇到的主要问题是,将utf-8编码的字符串与unicode编码的字符串混合在一起。

例如,考虑以下脚本。

2.py年

# encoding: utf-8
name = 'helló wörld from two'

一个.py

# encoding: utf-8
from __future__ import unicode_literals
import two
name = 'helló wörld from one'
print name + two.name

运行python one.py的输出是:

Traceback (most recent call last):
  File "one.py", line 5, in <module>
    print name + two.name
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)

在这个例子中,two.name是一个utf-8编码的字符串(不是unicode),因为它没有导入unicode_literals,而one.name是一个unicode字符串。当两者混合使用时,python尝试解码编码的字符串(假设它是ascii)并将其转换为unicode,但失败了。如果你这样做的话就行了。

如果对字符串进行编码并稍后尝试混合它们,同样的事情也可能发生。 例如,它可以工作:

# encoding: utf-8
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
    html = html.encode('utf-8')
print 'DEBUG: %s' % html

输出:

DEBUG: <html><body>helló wörld</body></html>

但是在添加import unicode_literals之后,它不会:

# encoding: utf-8
from __future__ import unicode_literals
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
    html = html.encode('utf-8')
print 'DEBUG: %s' % html

输出:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print 'DEBUG: %s' % html
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)

它失败,因为'DEBUG: %s'是一个unicode字符串,因此python尝试解码html。修复打印的两种方法是执行print str('DEBUG: %s') % htmlprint 'DEBUG: %s' % html.decode('utf-8')

我希望这有助于您理解使用unicode字符串时可能出现的问题。

同样在2.6(在python 2.6.5rc1+之前)中,unicode文本不能很好地处理关键字参数(issue4978):

例如,以下代码在不使用unicode文本的情况下工作,但在使用unicode文本的情况下失败,出现TypeError:keywords must be string

  >>> def foo(a=None): pass
  ...
  >>> foo(**{'a':1})
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
      TypeError: foo() keywords must be strings

我确实发现,如果添加unicode_literals指令,还应该添加如下内容:

 # -*- coding: utf-8

到.py文件的第一行或第二行。其他行,如:

 foo = "barré"

导致错误,例如:

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

相关问题 更多 >