Can someone explain me why in example below, print a
raises exception, while a.__str__() doesn't?
>>> class A:
... def __init__(self):
... self.t1 = "čakovec".decode("utf-8")
... self.t2 = "tg"
... def __str__(self):
... return self.t1 + self.t2
...
>>> a = A()
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u010d' in position 0: ordinal not in range(128)
>>> a.__str__()
u'\u010dakovectg'
>>> print a.__str__()
čakovectg
1 Answer 1
In Python 2 str must return an ASCII string. When you call __str__ directly you're skipping the step of Python converting the output of __str__ to an ASCII string (you could in fact return whatever you want from __str__, but you shouldn't). __str__ should not return a unicode object, it should return a str object.
Here's something you can do instead:
In [29]: class A(object):
...: def __init__(self):
...: self.t1 = u"c∃".encode('utf8')
...: def __str__(self):
...: return self.t1
...:
In [30]: a = A()
In [31]: print a
c∃
In [32]: str(a)
Out[32]: 'c\xe2\x88\x83'
In [33]: a.__str__()
Out[33]: 'c\xe2\x88\x83'
answered Aug 30, 2013 at 13:51
Phillip Cloud
25.9k12 gold badges72 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py