Python Reference · String Methods
Python str.isascii() method
Reference for Python str.isascii() (new in 3.7): test whether every character is in the ASCII range 0 to 127, and that an empty string returns True.
The str.isascii() method returns True if every character in the string is an ASCII character, meaning a code point from 0 to 127. That covers English letters, digits, ordinary punctuation, the space and control characters such as the newline. It was added in Python 3.7.
Unlike most is...() methods, an empty string returns True, because it contains no non-ASCII character. The check is fast, since CPython stores that information about each string.
print("hello!".isascii()) # True print("héllo".isascii()) # False
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.isascii()
| Name | Description |
|---|---|
| (none) | The method takes no arguments. |
Return value: True if all characters are in the range U+0000 to U+007F (or the string is empty); otherwise False.
Raises: nothing.
Usage notes
- Empty string is
True. Addand sif you need at least one character. - ASCII is a small subset of Unicode. Accented letters, curly quotes, the euro sign and emoji are not ASCII, even if they look ordinary.
- Not the same as
isalpha()orisalnum(). Those accept letters from every script. Combine them withisascii()for a strict check. - Predicts
encode("ascii"). Ifs.isascii()is true,s.encode("ascii")will not raiseUnicodeEncodeError. - Includes control characters. Newlines, tabs and the null character are ASCII. Use
isprintable()to exclude them. - Bytes objects have an
isascii()method with the same meaning. - Before Python 3.7, the usual workaround was a
try/exceptarounds.encode("ascii"), orall(ord(c) < 128 for c in s).
Related
str.isalnum(),str.isalpha(),str.isprintable(),str.encode(),ord(),ascii()- Lessons: Strings, String methods