打印变量

时间:2016-12-16 01:46:40

标签: 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']我收到错误消息时:

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>

我使用Python 2.7.12在Windows 10上工作 怎么可能在for循环之前打印好的所有东西,但是当我尝试打印一些碎片然后我被描述错误?

1 个答案:

答案 0 :(得分:3)

打印列表显示其内容的repr(),其中将非ASCII字符显示为转义码。打印内容直接将其编码到终端,在您的情况下,该终端似乎是一个Windows控制台,默认代码页为852.该代码页不支持一个或多个正在打印的字符。

示例(使用我的默认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字符时才有意义。