Unicode and exception strings

Rune Froysa rune.froysa at usit.uio.no
Mon Jan 12 02:41:43 EST 2004


Terry Carroll <carroll at tjc.com> writes:

> On 09 Jan 2004 13:18:39 +0100, Rune Froysa <rune.froysa at usit.uio.no>
> wrote:
> 
> >Assuming an exception like:
> >
> >  x = ValueError(u'\xf8')
> >
> >AFAIK the common way to get a string representation of the exception
> >as a message is to simply cast it to a string: str(x).  This will
> >result in an "UnicodeError: ASCII encoding error: ordinal not in
> >range(128)".
> >
> >The common way to fix this is with something like
> >u'\xf8'.encode("ascii", 'replace').  However I can't find any way to
> >tell ValueErrors __str__ method which encoding to use.
> 
> Rune, I'm not understanding what your problem is.
> 
> Is there any reason you're not using, for example, just repr(u'\xf8')?

The problem is that I have little control over the message string that
is passed to ValueError().  All my program knows is that it has caught
one such error, and that its message string is in unicode format.  I
need to access the message string (for logging etc.).

>          _display_text = _display_text + "%s\n" % line.decode('utf-8'))

This does not work, as I'm unable to get at the 'line', which is
stored internally in the ValueError class (and generated by its __str_
method).

Regards,
Rune Frøysa



More information about the Python-list mailing list