python - __str__ 返回 UnicodeEncodeError,但在其他方面有效 (u'\xa0')

标签 python python-2.7 python-3.x unicode encoding

我遇到了我生命中最奇怪的错误。

我正在修复我的 Hacker News API这段代码让我很头疼:

from hn import HN

hn = HN()


# print top stories from homepage
for story in hn.get_stories():
    print story.title
    print story

Story类一个__str__方法如下:

def __str__(self):
    """
    Return string representation of a story
    """
    return self.title

(这与 repo 中的代码有点不同。我不得不在这里进行大量调试。)

无论如何,输出是这样的:

Turn O(n^2) reverse into O(n)
Turn O(n^2) reverse into O(n)
My run-in with unauthorised Litecoin mining on AWS
My run-in with unauthorised Litecoin mining on AWS
Amazon takes away access to purchased Christmas movie during Christmas
Traceback (most recent call last):
  File "my_test_bot.py", line 11, in <module>
    print story
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 60: ordinal not in range(128)

我不知道为什么会失败。 __str__print story 语句都打印一个 unicode。那么为什么后者不起作用?

此外,print unicode(story) 工作正常(为什么??),但不幸的是我不能使用 unicode(),因为它与 py3 不兼容。

title 编码为:title.encode('cp850', errors='replace').decode('cp850')

这到底是怎么回事?我如何确保我的 API 适用于它可以找到的任何(意思是大多数)字符串并且兼容 py2 和 py3?

我有downloaded the page这就是现在离线调试时导致此错误的原因。

最佳答案

__str__ 返回一个字节数组,没有任何关于编码的信息,您的控制台应用程序可能会尝试将 __str__ 返回的任何内容编码为 ascii,但失败了。您可以尝试使用返回字符的 __unicode__this answer 中有更多信息.

是的,py3 只有 __str__ 元数据,因此您必须保留 __unicode__ 以实现兼容性

关于python - __str__ 返回 UnicodeEncodeError,但在其他方面有效 (u'\xa0'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20603810/

相关文章:

带有负值的 Python timedelta 问题

Python 找不到已安装的模块

python - virtualenvwrapper 不会在 mac os 上创建/bin/目录

python - Django 1.4 可以提供媒体文件服务,但不是静态的

python - python 列表理解中的 if-else

python - Pandas 到日期时间的转换运行缓慢/不运行

Python 以太坊区 block 链交易

python - 如何使 C 包装器(用 32 位 Python 编写)在运行 64 位 Python 的新机器上工作?

python - 如何生成波特图矩阵?

python - 如何直接从 python 脚本修改 Windows 10 路径变量