Home > python > ‘ascii’ codec can’t encode character: ordinal not in range(128)

‘ascii’ codec can’t encode character: ordinal not in range(128)

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.

Advertisements
Categories: python Tags: , ,
  1. February 1, 2013 at 16:54

    nice solution

  2. July 18, 2014 at 15:19

    Thanks.

  3. August 27, 2014 at 12:38

    Thank you so much for the help!

  4. May 7, 2015 at 23:43

    Your solution saved me thank you!

  5. July 29, 2015 at 20:52

    Thankkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!!!!!!

  6. November 6, 2015 at 17:29

    It works! Thanks

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: