Skip to content
Tutorials Center
My learning

Topics

Python Reference Β· String Methods

Python str.isprintable() method

Reference for Python str.isprintable(): detect control characters, newlines and other non-printable text, why the empty string is True, and the space exception.

The isprintable() method returns True if every character in the string is printable, or if the string is empty. Printable means the character is not a control character, a separator other than the ordinary space, or an unassigned or private code point. Letters, digits, punctuation and the ASCII space are printable. Newlines, tabs and the null character are not.

It is handy for checking input before logging it or showing it in a single line of a terminal.

Python
print("hello world".isprintable())   # True
print("hello\n".isprintable())       # False

Try it

Python Printable or not

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 Finding the culprit

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.isprintable()

This method takes no parameters.

Return value: True if all characters are printable or the string is empty; otherwise False.

Raises: nothing.

Usage notes

  • The empty string is True. This is unlike the other is...() tests such as isalpha(). Check bool(text) too if empty input should be rejected.
  • Space is special. The ASCII space " " is printable. Other space-like characters, such as the non-breaking space Β , are not, because their Unicode category is a separator other than the plain space.
  • Whitespace controls fail. \n, \r and \t make the result False, even though they are ordinary whitespace.
  • Invisible characters. Zero-width characters such as ​ are format characters and are not printable, which makes this method a quick way to spot hidden characters in pasted text.
  • Definition. A character is non-printable when its Unicode category is "Other" (Cc, Cf, Cs, Co, Cn) or "Separator" (Zl, Zp, Zs) with the sole exception of the ASCII space.
  • Related to repr(). repr() escapes exactly the characters that isprintable() rejects, which is how it keeps output readable.
  • Bytes have their own meaning and no isprintable().