unicode文本用于什么?

2024-06-25 23:29:17 发布

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

我对Python中的__future__.unicode_literals有一个奇怪的问题。在不导入unicode_literals的情况下,我得到正确的输出:

# encoding: utf-8
# from __future__ import unicode_literals
name = 'helló wörld from example'
print name

但是当我添加unicode_literals导入时:

# encoding: utf-8
from __future__ import unicode_literals
name = 'helló wörld from example'
print name

我得到这个错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 4: ordinal not in range(128)

unicode_literals是否将每个字符串编码为utf-8? 我应该做什么来覆盖这个错误?


Tags: nameinfromimportexample错误unicode情况
1条回答
网友
1楼 · 发布于 2024-06-25 23:29:17

您的终端或控制台无法让Python知道它支持UTF-8。

如果没有from __future__ import unicode_literals行,您将构建一个包含UTF-8编码字节的字节字符串。使用该字符串可以构建一个unicode字符串。

print必须以不同的方式处理这两个值;一个字节字符串被写入sys.stdout时保持不变。一个unicode字符串首先被编码为字节,而Python会为此参考sys.stdout.encoding。如果您的系统不能正确地告诉Python它支持什么编解码器,那么默认情况是使用ASCII。

系统无法告诉Python要使用的编解码器;sys.stdout.encoding设置为ASCII,对要打印的unicode值进行编码失败。

您可以在打印时手动编码到UTF-8来验证这一点:

# encoding: utf-8
from __future__ import unicode_literals
name = 'helló wörld from example'
print name.encode('utf8')

您也可以通过创建不带from __future__import语句的unicode文本来重现此问题:

# encoding: utf-8
name = u'helló wörld from example'
print name

其中u'..'也是unicode文本。

如果没有环境的详细信息,就很难说解决方案是什么;这在很大程度上取决于所使用的操作系统、控制台或终端。

相关问题 更多 >