close

[Solved] Python UnicodeEncodeError: ‘ascii’ codec can’t encode character in position 0: ordinal not in range(128)

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python UnicodeEncodeError: ‘ascii’ codec can’t encode character in position 0: ordinal not in range(128) in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python UnicodeEncodeError: ‘ascii’ codec can’t encode character in position 0: ordinal not in range(128) Error Occurs?

Today I get the following error Python UnicodeEncodeError: ‘ascii’ codec can’t encode character in position 0: ordinal not in range(128) in python.

How To Solve Python UnicodeEncodeError: ‘ascii’ codec can’t encode character in position 0: ordinal not in range(128) Error ?

  1. How To Solve Python UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) Error ?

    To Solve Python UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) Error I will answer my own question. Found an duplicated question. stackoverflow.com/questions/9942594/

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

    To Solve Python UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) Error I will answer my own question. Found an duplicated question. stackoverflow.com/questions/9942594/

Solution 1

Try this:

u'\u2013'.encode('utf-8')

Solution 2

I will answer my own question. Found an duplicated question. stackoverflow.com/questions/9942594/

But for simplicity, here is an elegant solution that works well with my use case:

def safe_str(obj):
    try: return str(obj)
    except UnicodeEncodeError:
        return obj.encode('ascii', 'ignore').decode('ascii')
    return ""

safe_str(u'\u2013')

Or simply use:

u'\u2013'.encode('ascii', 'ignore')

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read