0

I am reading a json file with python 3.5. In this file it have characters like "í". I would like to print it in that format. How do I make the below code print the character correctly?

t = 'í'
print(t)

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print(t)
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 0: ordinal not in range(128)
labjunky
  • 831
  • 1
  • 13
  • 22
  • Possible duplicate of [UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)](http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20) – Ken Y-N May 22 '17 at 03:48
  • 1
    I can't reproduce this—it prints fine for me. Are you certain that you're using Python 3? Only Python 2 should have that error in this circumstance. – Arya McCarthy May 22 '17 at 03:48
  • 1
    That's the error you get when you run it using Python 2 – Taku May 22 '17 at 03:49
  • print(sys.version_info) results in 3.6.1 – labjunky May 22 '17 at 05:06
  • The json file was opened using: with open('ep_meps_current.json', 'r', encoding='utf-8') as fp: meps = json.load(fp) – labjunky May 22 '17 at 05:15
  • Now I see that it runs fine on the command line, but not within sublime text 3. Running from the same virtualenv. – labjunky May 22 '17 at 05:28

4 Answers4

1

Try adding # -*- coding: iso-8859-15 -*- as the first or second line of your source file.

bokirov
  • 13
  • 1
  • 4
0

Use unicode format.

t = u'i'
print(t)

You have to add u before the character 'i' so that python understands it as unicode.

Taku
  • 31,927
  • 11
  • 74
  • 85
bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

Try this:

print(t.decode("utf-8"))
Taku
  • 31,927
  • 11
  • 74
  • 85
Robert
  • 33,429
  • 8
  • 90
  • 94
0

try this -

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
t = 'í'
print(t.encode("ascii" , "ignore"))
tom
  • 3,720
  • 5
  • 26
  • 48