unicode bit me
J. Cliff Dyer
jcd at sdf.lonestar.org
Fri May 8 15:04:55 EDT 2009
On Fri, 2009-05-08 at 07:53 -0700, anuraguniyal at yahoo.com wrote:
> #how can I print a list of object which may return unicode
> representation?
> # -*- coding: utf-8 -*-
>
> class A(object):
>
> def __unicode__(self):
> return u"©au"
>
> __str__ = __repr__ = __unicode__
>
Your __str__ and __repr__ methods don't return strings. You should
encode your unicode to the encoding you want before you try to print it.
class A(object):
def __unicode__(self):
return u"©au"
def get_utf8_repr(self):
return self.__unicode__().encode('utf-8')
def get_koi8_repr(self):
return self.__unicode__().encode('koi-8')
__str__ = __repr__ = self.get_utf8_repr
> a = A()
>
> try:
> print a # doesn't work?
> except UnicodeEncodeError,e:
> print e
> try:
> print unicode(a) # works, ok fine, great
> except UnicodeEncodeError,e:
> print e
> try:
> print unicode([a]) # what!!!! doesn't work?
> except UnicodeEncodeError,e:
> print e
> """
> Now how can I print a list of object which may return unicode
> representation?
> loop/map is not an option as it goes much deepr in my real code
> any can anyoen explain what is happening here under the hood?
> """
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list