To check if a string consists entirely of ASCII characters in Python, we can use several methods. Here are some commonly used approaches:
Method 1: Using the isascii() method of strings
In Python 3.7 and above versions, the string type provides an isascii() method. This method checks whether all characters in the string are ASCII characters. If they are, it returns True; otherwise, it returns False.
pythondef is_ascii(s): return s.isascii() # Example string = "Hello" print(is_ascii(string)) # Output: True string = "你好" print(is_ascii(string)) # Output: False
Method 2: Using the ord() function to verify character encoding
The ASCII character encoding range is 0 to 127. We can iterate over each character in the string, use the ord() function to obtain the ASCII value, and verify that this value falls within the range of 0 to 127.
pythondef is_ascii(s): return all(ord(c) <= 127 for c in s) # Example string = "Hello" print(is_ascii(string)) # Output: True string = "Café" print(is_ascii(string)) # Output: False
Method 3: Exception handling
Attempt to encode the string as ASCII. If successful, the string is considered entirely ASCII; if a UnicodeEncodeError exception is raised, it indicates the presence of non-ASCII characters.
pythondef is_ascii(s): try: s.encode('ascii') return True except UnicodeEncodeError: return False # Example string = "Hello" print(is_ascii(string)) # Output: True string = "Español" print(is_ascii(string)) # Output: False
Among these three methods, using the isascii() method is the most concise and efficient. However, note that it is only available in Python 3.7 and above versions. Other methods are compatible with all Python versions. In practical applications, we typically select the most suitable method based on the Python environment and specific requirements.