Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Short confusing example with unicode, print, and __str__

Reply
Thread Tools

Short confusing example with unicode, print, and __str__

 
 
Gerard Brunick
Guest
Posts: n/a
 
      03-05-2008
I really don't understand the following behavior:

>>> class C(object):

.... def __init__(self, s): self.s = s
.... def __str__(self): return self.s
....
>>> cafe = unicode("Caf\xe9", "Latin-1")
>>> c = C(cafe)
>>> print "Print using c.s:", c.s

Print using c.s: Café
>>> print "Print using just c:", c

Print using just c: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in
position 3: ordinal not in range(12
>>> str(c)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in
position 3: ordinal not in range(12

Why would "print c.s" work but the other two cases throw an exception?
Any help understanding this would be greatly appreciated.

Thanks in advance,
Gerard
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Problem with __str__ method and character encoding Chris Angelico Python 0 12-07-2012 02:33 PM
Re: Problem with __str__ method and character encoding peter Python 0 12-07-2012 02:22 PM
Difference of extern short *x and extern short x[]? Andre C Programming 5 07-17-2012 07:38 PM
grep example's use of $_ confusing me. Justin C Perl Misc 2 11-01-2010 01:34 PM
how to use __str__ and __repr__? Jim Newton Python 15 06-09-2004 01:21 PM



Advertisments