Python String isprintable()

In this tutorial, you will learn about the Python String isprintable() method with the help of examples.

The isprintable() method returns True if all characters in the string are printable. If not, it returns False.

Example

text = 'apple'

# returns True if text is printable result = text.isprintable()
print(result) # Output: True

isprintable() Syntax

The syntax of the isprintable() method is:

string.isprintable()

Here, isprintable() checks if string is printable or not.

Note:

  • Characters that occupy printing space on the screen are known as printable characters. For example letters and symbols, digits, punctuation, whitespace
  • Characters that do not occupy a space and are used for formatting is known as non-printable characters. For example line breaks, page breaks

isprintable() Parameters

The isprintable() method doesn't take any parameters.


isprintable() Return Value

The isprintable() method returns:

  • True - if all characters in the string are printable
  • False - if the string contains at least one non-printable character

Example 1: Python String isprintable()

text1 = 'python programming'

# checks if text1 is printable result1 = text1.isprintable()
print(result1) text2 = 'python programming\n'
# checks if text2 is printable result2 = text2.isprintable()
print(result2)

Output

True
False

In the above example, we have used the isprintable() method to check whether the text1 and text2 strings are printable or not.

Here,

  • text1.isprintable() - returns True because 'python programming' is printable string
  • text2.isprintable() - returns False because 'python programming\n' contains a non-printable character '\n'

That means if we print text2, it does not print '\n' character,

print(text2)
# Output: python programing

Example 2: isprintable() with Empty String

The isprintable() method returns True when we pass an empty string. For example,

empty_string = ' '

# returns True with an empty string print(empty_string.isprintable())

Output

True

Here, empty_string.isprintable() returns True.


Example 3: isprintable() with String Containing ASCII

# defining string using ASCII value 
text = chr(27) + chr(97)

# checks if text is printable if text.isprintable():
print('Printable') else: print('Not Printable')

Output

Not Printable

In the above example, we have defined the text string using ASCII. Here,

  • chr(27) - is escape character i.e. backslash \
  • chr(97) - is letter 'a'

The text.isprintable() code returns False since chr(27) + chr(97) contains non printable escape character.

Hence the program executes the else part.


Did you find this article helpful?