Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("hello!".isascii())    # True
print("héllo".isascii())     # False

Try it

Python Which strings are ASCII

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.

Python Combining with other checks

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

Python
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. Add and s if 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() or isalnum(). Those accept letters from every script. Combine them with isascii() for a strict check.
  • Predicts encode("ascii"). If s.isascii() is true, s.encode("ascii") will not raise UnicodeEncodeError.
  • 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/except around s.encode("ascii"), or all(ord(c) < 128 for c in s).