Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 461
gustavlarson Avatar asked Nov 17 '25 02:11

gustavlarson


1 Answers

# -*- coding: UTF-8 -*-

only affects the way Python decodes comments and string literals in your source, not the way standard output is configured, etc, etc. If you set your Mac's Terminal to UTF-8 (Terminal, Preferences, Settings, Advanced, International dropdown) and emit Unicode text to it after encoding it in UTF-8 (print name.encode("utf-8")), you should be fine.

like image 142
Alex Martelli Avatar answered Nov 19 '25 15:11

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!