Python中的Unicode错误时可变
问题描述:
#-*- coding: utf-8 -*-
import testapi.api
import testapi.ladder.analytics
if not len(sys.argv) == 2:
sys.exit("Error: League name was not set!!")
leagueNameId = sys.argv[1]
ladder = testapi.ladder.retrieve(leagueNameId, True)
print ladder
for i, val in enumerate(ladder):
print val['character']['name']
print lader
工作确定,我看到所有印刷没有任何问题,但是当print val['character']['name']
我得到错误信息:Python中的Unicode错误时可变
Traceback (most recent call last): File "getevent.py", line 16, in <module>
print val['character']['name'] File "J:\Program Files\Python2.7\lib\encodings\cp852.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-22: character maps to <undefined>
我在Windows 10与Python 2.7.12
工作在for
循环之前如何可能会打印好,但在尝试打印某些片段之后,我描述了错误?
答
打印列表显示其内容的repr()
,该内容显示非ASCII字符为转义码。打印内容直接将其编码到终端,在您的情况下,终端似乎是一个默认代码页为852的Windows控制台。该代码页不支持一个或多个要打印的字符。
例(与我的默认代码页437):
>>> L = [u'can\u2019t']
>>> print L
[u'can\u2019t']
>>> print L[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2019' in position 3: character maps to <undefined>
,但如果更改到支持的字符终端编码,与chcp 1252
:
>>> L = [u'can\u2019t']
>>> print L
[u'can\u2019t']
>>> print L[0]
can’t
顺便说一句,如果你尽管#-*- coding: utf-8 -*-
将对打印输出有任何影响,但不会。它仅声明源文件的编码,并且只在源中包含非ASCII字符时才重要。