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.

 

Comments

Add Comments

Name:
Comment:

 

About

As someone who has worked on Macs since 1989, I will use my experience to share tips and tricks with you on Fridays. As a Mac user since 1989, I have seen the evolution of Mac software and hardware, and I know how Mac computers work. I also know how to troubleshoot and fix Mac problems that can arise.

Schedule

ThursdayPython
FridayMacintosh
SaturdayInternet Tools
SundayOpen Topic
Monday Media Monday
TuesdayQA
WednesdaySnagIt for QA