python - 为什么我尝试在 Python 2.7 中打印字符串时遇到错误?

标签 python

我正在尝试使用

https://pypi.python.org/pypi/dbf

读取数据库文件。我正在尝试按如下方式打印记录:

for record in race_db:
    print record

这给了我一条错误消息

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc9 in position 4: ordinal not in range(128)

所以我尝试映射到unicode

string_record = [unicode(item) for item in record]

同样的事情。 utf-8:

string_record = [unicode(item, "utf8") for item in record]

TypeError: coercing to Unicode: need string or buffer, datetime.date found

我只是想要一些对字符串功能进行排序的功能,我做错了什么?我知道我可以成功循环所有记录,因为类似:

print 'blah'

工作正常。只是编码中的某些东西让我困惑。

最佳答案

单字节 \xC9 不是 UTF-8 中任何内容的有效编码。您需要弄清楚文本当前的编码方式 - 在本例中,很可能是 ISO 8859-1Windows-1252 。然后,相应地对其进行解码。

例如,如果是 Windows-1252,您将按如下方式对其进行解码:

string_record = 'foo \xc9 bar'
print string_record.decode('Windows-1252')  # Output: "foo É bar"

关于python - 为什么我尝试在 Python 2.7 中打印字符串时遇到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15845665/

相关文章:

python - 用python读取二进制文件

python - TF 中的索引操作

Python:如何使用 feedparser 和 etags 检查 RSS 更新

python - 使用 for 循环追加 3D 数组

python - 从scrapy中提取数据到数组中

python - 如何使用 Python、BeautifulSoup 和 mechanize 从表中提取 Web 数据

python - 使用 Pygame 定位移动图像/矩形

python - 使用新数据更新 Pandas 数据框,同时保留现有 ID 号

python - 将 HOCR 输出转换为字符串(用于正则表达式)的策略是什么?

python - 使用 -lwiringPy 在 C 中编译 Python 模块