在Python 2.6中使用unicode_literals有任何陷阱吗?
我们已经获得了在Python 2.6下运行的代码库。为了准备Python 3.0,我们开始添加:
从__future__导入unicode_literals
进入我们的.py
文件(我们对其进行修改)。我想知道是否还有其他人正在这样做并且遇到了任何非显而易见的陷阱(也许在花费大量时间进行调试之后)。
-
我处理unicode字符串的主要问题来源是将utf-8编码的字符串与unicode的字符串混合使用。
例如,考虑以下脚本。
py
# encoding: utf-8 name = 'helló wörld from two'
一个
# 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并失败。如果您这样做的话,那会起作用的print name + two.name.decode('utf-8')
。如果您对字符串进行编码并稍后尝试将其混合,则可能会发生相同的情况。例如,这有效:
# 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') % html
或print 'DEBUG: %s' % html.decode('utf-8')
。我希望这可以帮助您了解使用unicode字符串时的潜在陷阱。