我正在尝试编写一个函数,它可以在命令提示符和文件中打印内容。以下代码会出现编码/解码错误:
我得到了以下输出:
我尝试了所有我能想到的encode()/decode()组合,但都没有成功。如何解决这个错误?
import os
def pas(stringToProcess): #printAndSave
print stringToProcess
try: f = open('file', 'a')
except: f = open('file', 'wb')
print >> f, stringToProcess
f.close()
all = {u'title': u'Pi\xf1ata', u'albumname': u'New Clear War {EP}', u'artistname': u'Montgomery'}
pas(all['title'])
我得到了以下输出:
Piñata
Traceback (most recent call last):
File "new.py", line 17, in <module>
pas(all['title'])
File "new.py", line 11, in pas
print >> f, stringToProcess
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 2: ordinal not in range(128)
我尝试了所有我能想到的encode()/decode()组合,但都没有成功。如何解决这个错误?
all['title'].encode('utf8')
也可以正常工作。你尝试了什么? - Martijn Pieters