Removing non-ascii chars from a string in Python

July 13, 2012

I was processing some data from a database table, and the process was failing if a non-ascii character was passed. I didn't mind losing these characters, so needed a way to remove them from my string before processing.

This function can do that in Python:

def _removeNonAscii(s): return "".join(i for i in s if ord(i)<128)