How to check if string contains only unprintable characters and spaces?

Viewed 225

I have a string that looks a little something like this:

case0:

string0 = ' '

case1:

string1 = '\n\n'

case2:

string2 = '\n\n\n \n \n\n\n\n' 

case3:

string3 = ' test string12!. \n\n'

case4:

string4 = 'test string12!.'

I wish to allow only circumstances as seen in case 3 and case 4.

Using isprintable() would not allow case 3 to pass and allow case 0 to pass.

How do I detect if the string looks blank (e.g. in case 0, case 1 and case 2)?

2 Answers

Use the string methods isprintable() and isspace() and iterate through the string to check every character:

string1 = '\n\n'
not_printable = True
for char in string1:
    if char.isprintable() or not char.isspace():
        not_printable = False
if not_printable:    
    print('Not Printable')
else:
    print('Printable')

Output:

Not Printable

For a string containing printable character(s):

string3 = ' test string12!. \n\n'
not_printable = True
for char in string3:
    if char.isprintable() or not char.isspace():
        not_printable = False
if not_printable:
    print('Not Printable')
else:
    print('Printable')

Output:

Printable

You could also determine all of the nonprintable or space characters with this loop adapted from here:

unprintable = []

for ascii_val in range(2 ** 16):
    ch = chr(ascii_val)
    if not ch.isprintable() or ch.isspace():
        unprintable.append(ch)

And then make sure the string only contains those characters (10158 on my computer) like this:

string2 = '\n\n\n \n \n\n\n\n' 
if set(string2).issubset(set(unprintable)):
    print("Not Printable")
else:
    print('Printable')

Output:

Not Printable

The phrase "unprintable characters" is perhaps not well defined, but if we assume it be just whitespace characters, then we can try matching the regex pattern ^\s+$:

string2 = '\n\n\n \n \n\n\n\n'
if re.search(r'^\s+$', string2):
    print('string 2 has only whitespace')  # prints 'string 2 has only whitespace'

string3 = ' test string12!. \n\n'
if re.search(r'^\s+$', string3):
    print('string 3 has only whitespace')
Related