Python String isprintable() function returns True
if all characters in the string are printable or the string is empty, False
otherwise.
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="HitHello"
print(s.isprintable())
Output: False
because t is not a printable character.
s="HinHello"
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="HibHello"
print(s.isprintable())
print(s)
Output:
False
HHello
The b character is considered as non-printable.
s="HiaHello"
print(s.isprintable())
print(s)
Output:
False
HiHello
The a character is considered as non-printable.
s="Hiu0066Hello"
print(s.isprintable())
print(s)
s="Hiu0009Hello"
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
Reference: Official Documentation