【发布时间】:2014-01-03 10:10:39
【问题描述】:
我遇到了我一生中最奇怪的错误。
我正在修复我的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.encode和str.decode方法。要么只使用我不推荐的字节数组(py2 样式),要么只使用 unicode 字符串(使用str.encode或print(u"Hello")。顺便说一句,如果你想同时兼容 py2 和 py3 ,使用 print 作为函数而不是关键字。目前您的问题是您正在尝试使用 ascii 编解码器解码 unicode 字符。这将永远无法工作。永远。:P
标签: python python-2.7 python-3.x unicode encoding