Python 2.7.5:UnicodeEncodeError:'ascii'编解码器无法在位置570编码字符u'\ xa3':序数不在范围内128

问题描述

我在循环内的以下代码行遍历数据库表的记录并打印出注释字段:

output_file.write("\nTimesheet comment: {}".encode('utf-8').format(timesheet.comments))

它给出以下错误

UnicodeEncodeError:'ascii'编解码器无法在其中编码字符u'\ xa3' 位置570:序数不在范围内(128)

输出文件还将在多行中打印以下“ ^ M”。如何解决错误。如果没有简单的方法可以解决错误,甚至忽略奇怪的字符也是可以接受的解决方案,但是我不知道如何将条件附加到.format(...)函数

解决方法

我无法重现您的错误!

如果这样做;

.encode('utf-8').format(...)

然后,您首先将字符串转换为没有“ .format()”方法的“字节”对象,这意味着您将收到AttributeError。

如果您喜欢这样;

with open('some_file_name.txt','wb+') as output_file:
...     output_file.write("\nTimesheet comment: {}".format(u'\xa3').encode('utf-8'))
... 
with open('some_file_name.txt','r') as output_file:
...     print(output_file.read())
... 
Timesheet comment: £

对我来说很好。

换句话说;我无法重现您的错误,如果我(或任何人)要帮助您,则需要详细说明。