Fix UnicodeEncodeError with BBEdit
Quick Easy Fix
Have you ever gotten this error when running your Python code:
UnicodeEncodeError: 'ascii' codec can't encode character 'u2019' in position 16520: ordinal not in range(128) args = ('ascii', '<!DOCTYPE html>n<html lang="en">n <head>n <m...rigin="anonymous"></script>nnn </body>n</html>nn', 16520, 16521, 'ordinal not in range(128)') encoding = 'ascii' end = 16521 object = '<!DOCTYPE html>n<html lang="en">n <head>n <m...rigin="anonymous"></script>nnn </body>n</html>nn' reason = 'ordinal not in range(128)' start = 16520 with_traceback = <built-in method with_traceback of UnicodeEncodeError object>
This has been happening to me a lot when I convert code from PHP to Python. It was frustrating to fix the error. Someplace in my code is a piece of text that isn't translating well.
BBEdit to the Rescue!
Change the Python File Encoding!
By default the coding is Unicode (UTF-8)
However, if you change the file encoding to Western (ISO Latin 1) something magical happens when you save.
Unmappable character(s) detected.
If there's any Unicode in your file, it warns you and then tells you where the Unicode is so that you can fix it!
Once you fix all the errors the file will save and the UnicodeEncodeError should go away!
Sample Unmappable Characters dialog box that shows you what you need to fix!
If you get ordinal not in range(256) - Check out my solution.
If the error is results from a Database data, check out out this solution.