Search code examples
pythonmacosunicodepyobjc

Unicode problems in PyObjC


I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.

#! /usr/bin/env python
# -*- coding: UTF-8 -*-

from AddressBook import *

ab = ABAddressBook.sharedAddressBook()
people = ab.people()

for person in people:
    name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
    name

when I run this program, the output looks something like this:

...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...

Could someone please explain why the strings are in unicode, but the content looks like that?

I have also noticed that when I try to print the name I get the error

UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)

Solution

  • If you run the code in your question in the interactive console the interpreter will print the repr of "name" because of the last statement of the loop.

    If you change the last line of the loop from just "name" to "print name" the output should be fine. I've tested this with Terminal.app on a 10.5.7 system.