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

Python LogoOnce 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...

<p>
<script src="https://gist.github.com/slaptijack/31c9e9746ac4a258ad10.js"></script>
</p>
<noscript>
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)
</noscript>

<!--more-->

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():

<p>
<script src="https://gist.github.com/slaptijack/04790e6207dd877dd409.js"></script>
</p>
<noscript>
class Item(object):
    # ...snip...
    def name(self):
        # ...snip....
        return self.crest_type['name'].encode('utf-8')
</noscript>

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:

My Bookshelf

Reading Now

Other Stuff