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

UnicodeEncodeError: ‘ascii’ codec can’t encode character in position ordinal not in range(128) is an error which occurs when you try to decode data which is already decoded.

Today I try to explain why this error takes place and how to solve it, I will also add other solutions that could solve the error if possible.

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

This is is an error which occurs when you try to decode data which is already decoded.

You should avoid mixing between different errors. The error message should look like the error message bellow.

                                                                       #
UnicodeEncodeError: 'ascii' codec can't encode characters in position x-y: ordinal not in range(128)
                                                                       #

Bellow I will present multiple solutions some have worked for me and others have worked for other developers.

The Method that helped me get rid of this issue : never decode Unicode data in python and use a Unicode literal (u’…’)

In python you can only encode Unicode Data not decode it, since the data is already decoded and cannot be decoded twice.

The error occurs when you use decode when you should not be doing it. Just like in this example.

                                                                       #
print u'yourdata'.decode('utf-8')
                                                                       #

You should use a Unicode literal (u’…’) if you want to work with unicode values, just like this.

                                                                       #
print u'yourdata'
                                                                       #

If you have learned anything from this error, the best lesson to take is never decode Unicode data.

Thank you for reading this blog post, I hope your error is gone after trying my method.

Summing-up : 

That is it guys, this is the end of this article aka guide, I hope you found it useful in solving the error : UnicodeEncodeError ascii codec can’t encode character in position ordinal not in range 128 , make sure to support our work on Kofi, you do not have to but hey you can donate to the team.

Thank you for reading, keep coding and cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/