Created
October 1, 2012 12:39
-
-
Save takluyver/3811420 to your computer and use it in GitHub Desktop.
Is a string pure ASCII?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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