1

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
asked Aug 30, 2013 at 13:35

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.