Python String isprintable()

Filed Under: Python

Python String isprintable() function returns True if all characters in the string are printable or the string is empty, False otherwise.

python string isprintable()

Python String isprintable()

Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, except the ASCII space (0x20) which is considered printable.

Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string.

Let’s look at some examples of Python String isprintable() function.


s = 'Hi Hello World'

print(s.isprintable())

Output: True because all the characters are printable and space is considered as a printable character.


s = ''
print(s.isprintable())

Output: True because empty string is considered as printable.


s = 'Hi\tHello'
print(s.isprintable())

Output: False because \t is not a printable character.


s = 'Hi\nHello'
print(s.isprintable())

Output: False because \n is not a printable character.


s = 'Hi\'Hello'
print(s.isprintable())
print(s)

Output:


True
Hi'Hello

Let’s look at another example with some escape characters.


s = 'Hi\bHello'
print(s.isprintable())
print(s)

Output:


False
HHello

The \b character is considered as non-printable.


s = 'Hi\aHello'
print(s.isprintable())
print(s)

Output:


False
HiHello

The \a character is considered as non-printable.


s = 'Hi\u0066Hello'
print(s.isprintable())
print(s)

s = 'Hi\u0009Hello'
print(s.isprintable())
print(s)

Output:


True
HifHello
False
Hi	Hello

The \u0066 (f) is printable whereas \u0009 (\t) is non-printable.

Print all Non-Printable Characters List

Here is a simple code snippet to print the list of non-printable characters details.


count = 0
for codepoint in range(2 ** 16):
    ch = chr(codepoint)
    if not ch.isprintable():
        print(u'{:04x}'.format(codepoint))
        count = count + 1
print(f'Total Number of Non-Printable Unicode Characters = {count}')

Output:


0000
0001
0002
...
fffb
fffe
ffff
Total Number of Non-Printable Unicode Characters = 10249
If you are not familiar with f-prefixed string formatting, please read f-strings in Python.
You can checkout more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages