【发布时间】:2014-04-29 16:16:55
【问题描述】:
我在 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?
我应该怎么做才能覆盖这个错误?
【问题讨论】:
-
导入只对Python 2有效;当涉及到字符串文字时,它使 Python 2 的行为与 Python 3 一样。它使您的代码跨 Python 版本兼容。
-
问题出在你的终端,无法显示非ASCII字符。
-
由于您使用
print作为语句,因此您必须改用Python 2;我已经删除了让我失望的python-3.x标签。 -
@roippi:不,它完全能够显示已经编码的 UTF-8 字节。它使用 UTF-8 并不是与 Python 通信。
-
是的,我的措辞可以更好。
标签: python unicode encoding utf-8