2014年2月12日星期三

python: 解决两例UnicodeDecodeError错误

1. 使用string.Template
在safe_substitute({"key":"value"})的时候出现UnicodeDecodeError错误,把字典的内容打印出来,发现有一个key是:  'key':u'value'
value里面都是ASCII码,只是碰巧是unicide类型。
于是写个循环把字典转换一下:
dict_temp = {}
for key in dict_param:
value = dict_param[key]
if type(key)==types.UnicodeType:
key = key.encode('utf-8')
if type(value)==types.UnicodeType:
value = value.encode('utf-8')
dict_temp[key] = value
dict_param = dict_temp
然后解决!

2. 在使用 '%s'%(param)格式化字符串的时候出现UnicodeDecodeError
所有param中没有UnicodeString类型,于是在
if __name__=='__main__':
     #在这里加上
      reload(sys)
      sys.setdefaultencoding('utf-8')

然后解决

没有评论:

发表评论