How to Check if a String is ASCII in Python?

In this tutorial, I will explain how to check if a string is ASCII in Python. As a Python developer, I encountered a situation where I needed to check if a string was ASCII in one of my projects for my New York clients. Throughout this guide, I will use examples with USA-specific names to make the explanations more relatable.

ASCII and Unicode

Before getting into the methods for checking if a string is ASCII, it is important to understand the difference between ASCII and Unicode. ASCII (American Standard Code for Information Interchange) is a character encoding standard that uses 7-bit integers to represent characters. It includes characters such as letters (A-Z, a-z), digits (0-9), and some special characters (e.g., punctuation marks).

Unicode, on the other hand, is a more comprehensive encoding standard that can represent characters from almost all written languages in the world. It uses different encoding forms like UTF-8, UTF-16, and UTF-32, which can represent over a million unique characters.

Methods to Check if a String is ASCII

Python provides various ways to check if a string is ASCII.

Read How to Sort an Array in Python?

Method 1: Use the isascii() Method

Python 3.7 introduced the isascii() method for strings, which returns True if all characters in the string are ASCII, and False otherwise. This method is simple and efficient.

Example:

def check_ascii_using_isascii(s):
    return s.isascii()

# Example usage
name = "JohnDoe"
print(check_ascii_using_isascii(name))  

name_with_accent = "José"
print(check_ascii_using_isascii(name_with_accent)) 

Output:

True
False

I have executed the above example code and added the screenshot below.

Check if a String is ASCII in Python

In this example, the string “JohnDoe” contains only ASCII characters, so isascii() returns True. However, the string “José” contains a non-ASCII character (é), so the method returns False.

Check out How to Find the Number of Elements in a Python Array?

Method 2: Use a Custom Function with ord()

Another method involves creating a custom function that iterates over each character in the string and checks if its Unicode code point is within the ASCII range (0-127).

Example:

def check_ascii_custom(s):
    return all(ord(c) < 128 for c in s)

# Example usage
city = "NewYork"
print(check_ascii_custom(city)) 

city_with_symbol = "San José"
print(check_ascii_custom(city_with_symbol))  

Output:

True
False

I have executed the above example code and added the screenshot below.

How to Check if a String is ASCII in Python

In this example, the ord() function is used to get the Unicode code point of each character. The function returns True only if all characters in the string have code points less than 128.

Check out How to Count Occurrences in Python Arrays?

Method 3: Use Encoding and Decoding

You can also check if a string is ASCII by attempting to encode it to ASCII and catching any encoding errors. If the string can be encoded without errors, it is ASCII.

Example:

def check_ascii_encoding(s):
    try:
        s.encode('ascii')
        return True
    except UnicodeEncodeError:
        return False

# Example usage
state = "California"
print(check_ascii_encoding(state))  
state_with_accent = "Califórnia"
print(check_ascii_encoding(state_with_accent))  

Output:

True
False

I have executed the above example code and added the screenshot below.

Check if a String is ASCII in Python Encoding and Decoding

In this method, the string “California” can be encoded to ASCII without any issues, so the function returns True. The string “Califórnia” contains a non-ASCII character (ó), so encoding it to ASCII raises a UnicodeEncodeError , and the function returns False.

Read How to Remove NaN from Array in Python?

Applications

Let us see some real-time applications for checking if a string is ASCII in Python.

1. Filter User Inputs

When building web applications or APIs, you might want to ensure that user inputs are ASCII to prevent issues with downstream systems.

Example:

def filter_user_input(user_input):
    if check_ascii_using_isascii(user_input):
        return user_input
    else:
        return "Invalid input: Non-ASCII characters detected."

# Example usage
input_name = "Emily"
print(filter_user_input(input_name))  # Output: Emily

input_name_with_accent = "Emília"
print(filter_user_input(input_name_with_accent))  # Output: Invalid input: Non-ASCII characters detected.

Check out How to Find the Sum of an Array in Python?

2. Data Cleaning in Text Analysis

When performing text analysis on large datasets, you might need to filter out non-ASCII characters to simplify processing.

Example:

def clean_text(text):
    return ''.join(c for c in text if ord(c) < 128)

# Example usage
paragraph = "The quick brown fox jumps over the lazy dog in São Paulo."
cleaned_paragraph = clean_text(paragraph)
print(cleaned_paragraph)  # Output: The quick brown fox jumps over the lazy dog in So Paulo.

Read How to Append to an Array in Python?

3. Ensure Compatibility with Legacy Systems

Legacy systems often only support ASCII characters. Ensuring that strings are ASCII can prevent compatibility issues.

Example:

def ensure_compatibility(text):
    if check_ascii_encoding(text):
        return text
    else:
        return "Error: Non-ASCII characters present."

# Example usage
product_name = "Laptop"
print(ensure_compatibility(product_name))  # Output: Laptop

product_name_with_symbol = "Laptóp"
print(ensure_compatibility(product_name_with_symbol))  # Output: Error: Non-ASCII characters present.

Check out How to Iterate Through a 2D Array in Python?

Conclusion

In this tutorial, we explored various methods to check if a string is ASCII in Python. Whether you use the isascii() method, a custom function with ord() , or encoding and decoding, each method has its advantages. I covered some applications along with examples.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.