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 work ok and I see all printed without any problem but when print val['character']['name'] I got error message:

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>

I work on Windows 10 with Python 2.7.12
How it is possible that before for loop all is printed ok but after when I try to print some fragments then I got described error?

1 Answer 1

3

Printing lists displays the repr() of its content, which shows non-ASCII characters as escape codes. Printing the content directly encodes it to the terminal, which in you case appears to be a Windows console with a default code page of 852. That code page doesn't support one or more of the characters being printed.

Example (with my default 437 code page):

>>> 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>

But if you change to a terminal encoding that supports the character, with chcp 1252:

>>> L = [u'can\u2019t']
>>> print L
[u'can\u2019t']
>>> print L[0]
can’t

By the way, if you thought #-*- coding: utf-8 -*- would have any effect on printing output, it doesn't. It declares the encoding of your source file only, and only matters if you have non-ASCII characters in your source.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.