Computer >> Computer tutorials >  >> Programming >> Python

How to check if a string in Python is in ASCII?


The simplest way is to loop over the characters of the string and check if each character is ASCII or not. 

example

def is_ascii(s):
    return all(ord(c) < 128 for c in s)
print is_ascii('ӓmsterdӒm')

Output

This will give the output:

False

But this method is very inefficient. A better way is to decode the string using str.decode('ascii') and check for exceptions. 

example

mystring = 'ӓmsterdӓm'
try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "Not an ASCII-encoded string"
else:
    print "May be an ASCII-encoded string"

Output

This will give the output:

Not an ASCII-encoded string