2016-12-16 85 views
1
#-*- 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循環之前如何可能會打印好,但在嘗試打印某些片段之後,我描述了錯誤?

回答

2

打印列表顯示其內容的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字符時才重要。