viernes, 17 de julio de 2009

UnicodeEncodeError: 'ascii' codec can't encode character XXX

 Yet another text-format error in python (personal error, of course)...  while I was trying to store in file a joined list (through list comprehension), one or more of the characters of one the fields that are being joined generate the following 'friendly message':

Traceback (most recent call last):
  File "stations.py", line 62, in
  exit(main())
  File "stations.py", line 16, in main
  record.append(str(element.text))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 7: ordinal not in range(128)

 to avoid it, instead of trying to cast into a string the variable, you could use the repr() function... 

repr(object)
  Return a string containing a printable representation of an object.
  (http://docs.python.org/library/functions.html)

Example:

>>> caca = u'\u2603'
>>> print caca

>>> str(caca)
Traceback (most recent call last):
  File "", line 1, in
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2603' in position 0: ordinal not in range(128)
>>> repr(caca)
"u'\\u2603'"

solution from:
http://blog.codekills.net/archives/45-str...-yer-probably-doin-it-wrong..html

1 comentario:

  1. This is a known issue between different versions of the python interpreter that adds support for the 3.0 version.

    Advice: Avoid the "intermediate" version (a.k.a: 2.6 - 2.7) , stick with the 2.4 version until the ashes settle down over 3.0 and then jump into 3.0 directly.

    One can still use this intermediate version, but remember: the code will be more cumbersome and with extra code that will be there forever.

    ResponderEliminar