UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4:ordinal not in range(128)

写爬虫程序(如下)的时候,出现题述错误

def printUnivList(ulist, num):
    print("{:^10}\t{:^6}\t{:^10}".format("ranking", "college", "score"))
    for i in range(num):
        u = ulist[i]
        print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1],u[2]))

错误提示
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4:ordinal not in range(128)_第1张图片

原因:
在python2.7下,将字符串写入到文件时会出现”UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0’ in position”的错误,原因是由于python基于ASCII处理字符的,当出现不属于ASCII的字符时,会出现错误信息。

添加如下代码:

import sys
reload(sys)
sys.setdefaultencoding( "utf-8")

运行正常,显示如下:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4:ordinal not in range(128)_第2张图片

参考:
python2.x 默认编码问题http://www.cnblogs.com/work115/p/5924446.html

你可能感兴趣的:(python,爬虫,python)