Tuesday, July 24, 2012

Python: UnicodeEncodeError: 'ascii' codec can't encode character in position : ordinal not in range(128)

If you get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Use the .encode() method instead of using str():


a = u'bats\u00E0'
print a # batsà
print str(a) # UnicodeEncodeError: 'ascii' codec can't encode ...
print a.encode('utf-8') # batsà


Reference:
http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20