QA Graphic

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!

The easy quick fix I found is in the Text Status Bar in BBEdit. The text status bar shows the file encoding,

B B Edit File Encoding
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 Detected
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!

Unmappable Characters Dialog
Sample Unmappable Characters dialog box that shows you what you need to fix!

Alternative 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.

 

About

A Mac veteran since 1989, I'm here to share my experience with tips and tricks every Friday. Witnessing the evolution of Mac software and hardware firsthand, I've gained a deep understanding of how these machines work and can help you troubleshoot any issues that may come up.

Schedule

SundayOpen Topic
MondayMedia Monday
TuesdayQA
WednesdayAffinity
ThursdayBBEdit
FridayMacintosh
SaturdayInternet Tools