Short confusing example with unicode, print, and __str__

Discussion in 'Python' started by Gerard Brunick, Mar 5, 2008.

  1. 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(128)
    >>> 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(128)

    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
     
    Gerard Brunick, Mar 5, 2008
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dick Moores

    Unicode is confusing me

    Dick Moores, Feb 10, 2007, in forum: Python
    Replies:
    0
    Views:
    409
    Dick Moores
    Feb 10, 2007
  2. David Geering

    longs, long longs, short short long ints . . . huh?!

    David Geering, Jan 8, 2007, in forum: C Programming
    Replies:
    15
    Views:
    814
    Keith Thompson
    Jan 11, 2007
  3. Replies:
    4
    Views:
    1,081
    Kaz Kylheku
    Oct 17, 2006
  4. keto
    Replies:
    0
    Views:
    1,343
  5. Ioannis Vranos

    unsigned short, short literals

    Ioannis Vranos, Mar 4, 2008, in forum: C Programming
    Replies:
    5
    Views:
    933
    Eric Sosman
    Mar 5, 2008
  6. someone

    unicode confusing

    someone, May 25, 2009, in forum: Python
    Replies:
    4
    Views:
    472
    Paul Boddie
    May 26, 2009
  7. Justin C

    grep example's use of $_ confusing me.

    Justin C, Oct 29, 2010, in forum: Perl Misc
    Replies:
    2
    Views:
    300
    Justin C
    Nov 1, 2010
  8. Andre
    Replies:
    5
    Views:
    765
    Keith Thompson
    Jul 17, 2012
Loading...