unicode error

Scott David Daniels scott.daniels at acm.org
Fri Mar 17 17:00:37 EST 2006


Allerdyce.John at gmail.com wrote:
> I have this python code:
> print >> htmlFile, "<div id=\"track" + unicode(1) + "\"
> style=\"width: 200px; height:18px;\">";
> 
> 
> But that caues this error, and I can't figure it out why. Any help is
> appreicate
>  File "./run.py", line 193, in ?
>     print >> htmlFile, "<div id=\"track" + unicode(1) + "\"
> style=\"width: 200px; height:18px;\">";
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9:
> ordinal not in range(128)
> 
> Thanks.
> 
You can make the code easier to read by using single quotes to quote
strings with double quotes inside:

      print >> htmlFile, ('<div id="track' + unicode(1) +
                          '" style="width: 200px; height:18px;">')

Or even better:

      print >> htmlFile, (u'<div id="track%s" '
                  u'style="width: 200px; height:18px;">') % unicode(1)

The unicode(1) confuses me -- you are converting an integer to its
string representation in unicode (do you know that?), not picking a
particular character.

      print >> htmlFile, (u'<div id="track%d" style="width: 200px; '
                          u'height:18px;">') % (1,)

And if you don't mean to be writing unicode, you could use:

      print >> htmlFile, ('<div id="track%d" style="width: 200px; '
                          'height:18px;">') % (1,)

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list