我遇到了我生命中最奇怪的错误。
我正在修复我的 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/