Python String isprintable()
Method
The isprintable() method in Python is used to check whether all characters in a string are printable. This is helpful when validating user input, reading files, or filtering special characters.
Syntax
string.isprintable()
Returns:
True
– if all characters are printable (including space)False
– if at least one character is not printable (like\n
,\t
, etc.)
Example 1: Basic Usage
text = "Hello123!"
print(text.isprintable())
True
Example 2: Non-Printable Characters
text = "Hello\nWorld"
print(text.isprintable())
False
\n
(newline character) is not printable, so the result is False
.
Example 3: Space and Symbols
text = "Python 3.10 @#%"
print(text.isprintable())
True
Spaces and symbols like @
, #
, %
are considered printable characters.
Use Case: Filtering Unwanted Characters
Suppose you're processing user data or reading input from a file. You might want to ensure that it doesn't contain control characters like tabs or newlines.
user_input = "Hello\tWorld"
if not user_input.isprintable():
print("Input contains non-printable characters.")
Common Mistakes
- Empty string:
"".isprintable()
returnsTrue
. An empty string has no characters, and thus no non-printable ones. - Thinking
isprintable()
checks for only alphabets – it includes all printable characters, even symbols.
Interview Tip
isprintable()
can be useful in data validation questions. If asked to validate clean input or sanitize data, think about it!
Summary
isprintable()
checks if all characters in a string are printable- Printable includes letters, digits, symbols, and whitespace
- Control characters like newline (
\n
) or tab (\t
) are not printable
Practice Problem
Write a program that asks the user to enter a string and tells whether it’s fully printable or not.
text = input("Enter a string: ")
if text.isprintable():
print("All characters are printable!")
else:
print("String contains non-printable characters.")