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.
print("hello world".isprintable()) # True print("hello\n".isprintable()) # 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.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 otheris...()tests such asisalpha(). Checkbool(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,\rand\tmake the resultFalse, 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 thatisprintable()rejects, which is how it keeps output readable. - Bytes have their own meaning and no
isprintable().
Related
str.isspace(),str.isascii(),str.isalnum(),repr(),ascii()- Lessons: String methods, Strings