Skip to content

Instantly share code, notes, and snippets.

@takluyver
Created October 1, 2012 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takluyver/3811420 to your computer and use it in GitHub Desktop.
Save takluyver/3811420 to your computer and use it in GitHub Desktop.
Is a string pure ASCII?
def is_ascii(x):
"""Checks whether a string (unicode or bytes) is pure ASCII.
Works on Python 2.6 and above, including Python 3.
"""
if isinstance(x, bytes):
x = x.decode('latin-1') # This always succeeds.
try:
x.encode('ascii')
except UnicodeEncodeError:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment