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.
Python code
17 linesdef 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
'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
- Use the built‑in `str.isascii()` method: `return text.isascii()`
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.