当前位置: 移动技术网 > IT编程>脚本编程>Python > python2 ‘ascii‘ codec can‘t encode / decode 错误

python2 ‘ascii‘ codec can‘t encode / decode 错误

2020年07月14日  | 移动技术网IT编程  | 我要评论

参考:
用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 '-'

本文地址:https://blog.csdn.net/Scarlett_ma/article/details/107320202

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网