您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python 2.6中使用unicode_literals有任何陷阱吗?

在Python 2.6中使用unicode_literals有任何陷阱吗?

我处理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') % htmlprint 'DEBUG: %s' % html.decode('utf-8')

我希望这可以帮助您了解使用unicode字符串时的潜在陷阱。

python 2022/1/1 18:39:14 有254人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶