UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019'

Posted on in Programming

cover image for article

Once again I was working on some Python code for EVE Online. This particular bit of code gathers a list of kills for a particular region and then summarizes that data in a daily report. Everything had been working properly, until one day...

Traceback (most recent call last):
  File "/Users/scott/Dev/Scripts/Slaptijack/EVE/loss_report/report.py", line 163, in <module>
    main()
  File "/Users/scott/Dev/Scripts/Slaptijack/EVE/loss_report/report.py", line 159, in main
    print(template.render(context))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6711: ordinal not in range(128)

The problem was in my Item class. My name() method (which was also used by __str__() and __unicode__()) was throwing this error on the name of a particular item that included a non-ASCII character. The trick was to encode() the text when returning from name():

class Item(object):
    # ...snip...
    def name(self):
        # ...snip....
        return self.crest_type['name'].encode('utf-8')

If you like the idea of a video game you can write code against, check out EVE Online's free trial. That link will give you 21 days free versus the usual 14.

Related Reading

Slaptijack's Koding Kraken