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

参考: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 '-'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值