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

This error is raised when trying to encode a Unicode string using the ASCII codec, and the string contains a character that is not within the ASCII range (0-127). The specific character causing the error is the non-breaking space (U+00A0).

Here is a code snippet that demonstrates this error:

text = u"Hello,\xa0world!"  # the non-breaking space (U+00A0) is causing the error
except Exception as e:

Watch a course Python - The Practical Guide

To fix this error, you can use a different encoding that supports the character in question, such as UTF-8:

text = u"Hello,\xa0world!"

or you can remove or replace the character causing the error with a character in the ASCII range.

text = u"Hello, world!"