Python String isprintable()

The Python String isprintable() method is a built-in function that returns true if all the characters in a string are printable or if the string is empty. If not, it returns False.

What are printable characters in Python?

In Python, the character that occupies printing space on the screen is known as a printable character.

Examples of Printable characters are as follows –

  • Alphabets
  • Digits
  • whitespace
  • symbols and punctuation

Syntax

The Syntax of isprintable() method is:

string.isprintable()

Parameters

The isprintable() method does not take any parameters.

Return Value

The isprintable() method returns

  • True if the string is empty or all the character in the string is printable
  • False if the string contains at least one non-printable character

Example 1: Working of isprintable() method

# valid text and printable
text = 'These are printable characters'
print(text)
print(text.isprintable())

# \n is not printable
text = '\nNew Line is printable'
print(text)
print(text.isprintable())

# \t is non printable
text = '\t tab is printable'
print(text)
print(text.isprintable())

# empty character is printable
text = ''
print('\nEmpty string printable?', text.isprintable())

Output

These are printable characters
True

New Line is printable       
False
         tab is printable   
False

Empty string printable? True

Example 2: How to use isprintable() in the actual program

In the below Program, we will iterate the given text to check and count how many non-printable characters are there. If we find any non-printable characters we will be replacing it with empty characters and finally, we will output the printable characters into ‘newtext’ variable which can print all the characters.

text = 'Welcome to ItsMyCode,\nPython\tProgramming\n'
newtext = ''

# Initialising the counter to 0
count = 0

# Iterate the text, count the non-printable characters
# replace non printable characters with empty string
for c in text:
    if (c.isprintable()) == False:
        count += 1
        newtext += ' '
    else:
        newtext += c
print("Total Non Printable characters count is:", count)
print(newtext)

Output

Total Non Printable characters count is: 3
Welcome to ItsMyCode, Python Programming 
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like