How to Detect if a String Contains Only ASCII in Python

This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.

Easy Python 3.9+ Aug 9, 2026 Strings & text 17 views 0 copies

Python code

17 lines
Python 3.9+
def is_ascii_only(text: str) -> bool:
    """Return True if all characters in text are ASCII, False otherwise."""
    return all(ord(char) < 128 for char in text)


if __name__ == "__main__":
    # Test cases
    samples = [
        "Hello, world!",
        "Café au lait",
        "日本語テキスト",
        "ASCII only 123",
        "Emoji 😀 test",
        "",
    ]
    for sample in samples:
        print(f"{sample!r:30} -> {is_ascii_only(sample)}")

Output

stdout
'Hello, world!'        -> True
'Café au lait'         -> False
'日本語テキスト'        -> False
'ASCII only 123'       -> True
'Emoji 😀 test'        -> False
''                     -> True

How it works

The function uses ord(char) < 128 to test each character. ASCII characters have Unicode code points from 0 to 127, so any character with a code point 128 or above is non‑ASCII. The all() generator returns True only if every character passes the test. An empty string returns True because all() on an empty iterable is vacuously true.

Common mistakes

  • Using `char.isascii()` on a string returns True if all characters are ASCII, but forgetting that it's a method of `str`, not a standalone function.
  • Assuming non‑ASCII characters are only non‑English letters; emojis and special symbols also have code points above 127.
  • Not accounting for empty strings, which correctly return True but might be unexpected.

Variations

  1. Use the built‑in `str.isascii()` method: `return text.isascii()`
  2. Use a regex pattern: `re.fullmatch(r'[\x00-\x7F]*', text)` to match only ASCII characters.

Real-world use cases

  • Validate user input before storing it in legacy systems that only support ASCII encoding.
  • Check whether a string can be safely sent over protocols that require ASCII-only payloads, like certain API headers.
  • Filter out non‑ASCII characters from filenames or log entries that must be portable across systems.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.