close

[Solved] UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128)

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: 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 UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128) Error Occurs?

Today I get the following error UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128) in python.

How To Solve UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128) Error ?

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

    To Solve UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) Error I found elegant work around for me to remove symbols and continue to keep string as string in follows:

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

    To Solve UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) Error I found elegant work around for me to remove symbols and continue to keep string as string in follows:

Solution 1

In shell:

  1. Find supported UTF-8 locale by the following command:locale -a | grep "UTF-8"
  2. Export it, before running the script, e.g.:export LC_ALL=$(locale -a | grep UTF-8) or manually like:export LC_ALL=C.UTF-8
  3. Test it by printing special character, e.g. :python -c 'print(u"\u2122");'

Above tested in Ubuntu.

Solution 2

I found elegant work around for me to remove symbols and continue to keep string as string in follows:

yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')

It’s important to notice that using the ignore option is dangerous because it silently drops any unicode(and internationalization) support from the code that uses it, as seen here (convert unicode):

>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'

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