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).
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:
A python code that raises UnicodeEncodeError
text = u"Hello,\xa0world!" # the non-breaking space (U+00A0) is causing the error
try:
text.encode('ascii')
except Exception as e:
print(e)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
To fix this error, you can use a different encoding that supports the character in question, such as UTF-8:
Encode text with utf-8 in Python
text = u"Hello,\xa0world!"
print(text.encode('utf-8'))or you can remove or replace the character causing the error with a character in the ASCII range.
Encode text with ascii in Python
text = u"Hello, world!"
print(text.encode('ascii'))