Archive
Posts Tagged ‘UnicodeEncodeError’
Print unicode text to the terminal
September 2, 2012
2 comments
Problem
I wrote a script in Eclipse-PyDev that prints some text with accented characters to the standard output. It runs fine in the IDE but it breaks in the console:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 11: ordinal not in range(128)
This thing bugged me for a long time but now I found a working solution.
Solution
Insert the following in your source code:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
I found this trick here. “This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.”
Related
‘ascii’ codec can’t encode character: ordinal not in range(128)
March 29, 2012
6 comments
Problem
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 1: ordinal not in range(128)
Solution
def encode(text):
"""
For printing unicode characters to the console.
"""
return text.encode('utf-8')
Or:
reload(sys)
sys.setdefaultencoding("latin-1")
a = u'\xe1'
print str(a) # no exception
This tip is from here.
Categories: python
ascii, unicode, UnicodeEncodeError
