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

在Python 2.6中使用unicode_literals有任何陷阱吗?,第1张

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

我处理unipre字符串的主要问题来源是将utf-8编码的字符串与unipre的字符串混合使用。

例如,考虑以下脚本。

py

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

一个

# encoding: utf-8from __future__ import unipre_literalsimport twoname = '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.nameUnipreDepreError: 'ascii' prec can't depre byte 0xc3 in position 4: ordinal not in range(128)

在此示例中,

two.name
是utf-8编码的字符串(不是unipre),因为它没有导入
unipre_literals
,并且
one.name
是unipre字符串。当您将两者混合使用时,python会尝试解码编码后的字符串(假设它是ascii)并将其转换为unipre并失败。如果您这样做的话,那会起作用的
printname + two.name.depre('utf-8')

如果您对字符串进行编码并稍后尝试将其混合,则可能会发生相同的情况。例如,这有效:

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

输出:

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

但是添加后,

import unipre_literals
它不会:

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

输出:

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

它失败,因为

'DEBUG: %s'
是unipre字符串,因此python尝试解码
html
。修复打印件的几种方法正在执行
printstr('DEBUG: %s') % html
print 'DEBUG: %s' % html.depre('utf-8')

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5623414.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存