参考:Python 2.x 中的 ‘ascii’ codec can’t encode / decode 错误
用Python 2.x会经常碰到一个错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
原因:在Python中把一个Unicode类转化为 0 和 1 的过程叫做Encoding。 把 0 和 1 反转为Unicode类的过程叫做Decoding。
在Python 2.7版本里,ASCII是默认的Encoding和Decoding的方法。
具体理解,参考上面链接。这里讲解如何解决问题:
原来:
def get_make(lists):
if len(lists[-1]) >= 29 and lists[-1] is not None:
return str(lists[-1][9])
else:
return '-'
报错:
File "/home/marq/IFSClickThroughDataProcessTaskNew.py", line 67, in get_make
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
解释:无法用默认的ASCII编码Decode lists[-1][9],因为这个文字的数值已经超过了0 - 127这个范围。原因,str()中喂入python默认的ASCII码字符,而这里喂入的是Unicode字符,故去掉str,因本身就是string,无需用str来转换,省的格式不匹配:
def get_make(lists):
if len(lists[-1]) >= 29 and lists[-1] is not None:
return lists[-1][9] # 去掉str,理由python2.X默认是ascii
else:
return '-'