栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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字符串时的潜在陷阱。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号