Python UnicodeEncodeError Exception
Example
A UnicodeEncodeError occurs if a character cannot be encoded:
text = "caf\u00e9"
print(text.encode("ascii"))
Try it Yourself »
Definition and Usage
The UnicodeEncodeError exception occurs when a string has a character that cannot be encoded (changed to bytes) with the given encoding.
In the example, \u00e9 is the letter é. ASCII only has 128 characters, and é is not one of them.
Tip: UTF-8 can encode all characters: text.encode("utf-8").
Exception Handling
Example
Handling the UnicodeEncodeError in a try...except statement:
text = "caf\u00e9"
try:
print(text.encode("ascii"))
except UnicodeEncodeError:
print("The text has characters that ASCII cannot store")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.