【发布时间】:2015-03-30 04:22:29
【问题描述】:
我对 python 中的编码相当困惑。我有以下字符串。
s = "Caf\xe9/Coffee/Tea"
我想让它成为一个 unicode 字符串,以便它能够正确显示。以下作品:
t = u"Caf\xe9/Coffee/Tea"
print t
输出是“Café/Coffee/Tea”
但是如果我尝试
r = unicode(s)
我收到错误“UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 3: ordinal not in range(128)”
执行此操作时,我什至没有尝试将 unicode 字符串显示到控制台(我最近了解到的称为“heisenbug”)。但似乎我的控制台可以打印 unicode,所以我真的不明白这个问题。
如果重要的话,这是 python 2.7。
【问题讨论】:
-
该字符串(字节)已被编码。你需要
.decode它来获取一个unicode对象。 -
如果没有什么能阻止你回到 Python 2,我建议切换到 Python 3 - 你对 Unicode 的困惑会少得多。
-
是的。我想切换到 python 3,但我正在使用 python 的 anaconda 发行版......而且它仍然在 2.7 上。
标签: python unicode encoding utf-8