python中解决UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position

UnicodeEncodeError: 'ascii' codec can't encode characters in position:

>>> import logging
>>> a = u"0/aaaa/中国.jpg"
>>> logger = logging.getLogger()
>>> logger.setLevel("DEBUG")
>>> b = a.split("/")
>>> print b
[u'0', u'aaaa', u'\u4e2d\u56fd.jpg']
>>> logging.info('{0} {1}'.format(b[0], b[2]))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

>> print sys.getdefaultencoding()
ascii

解决方式1,修改全局的默认encodeing:

#!/usr/bin/env python    
#encoding: utf-8  
import sys   #引用sys模块进来,并不是进行sys的第一次加载  
reload(sys)  #重新加载sys  
sys.setdefaultencoding('utf8')  ##调用setdefaultencoding函数

解决方式2:仅仅修改当前编码

logging.info('{0} {1}'.format(b[0], b[2].encode("utf8")))

python_encode_decoce

发表评论

电子邮件地址不会被公开。 必填项已用*标注