Test if a python string is printable

As you’ve said the string module has printable so it’s just a case of checking if all the characters in your string are in printable:

>>> hello = 'Hello World!'
>>> bell = chr(7)
>>> import string
>>> all(c in string.printable for c in hello)
True
>>> all(c in string.printable for c in bell)
False

You could convert both strings to sets – so the set would contain each character in the string once – and check if the set created by your string is a subset of the printable characters:

>>> printset = set(string.printable)
>>> helloset = set(hello)
>>> bellset = set(bell)
>>> helloset
set(['!', ' ', 'e', 'd', 'H', 'l', 'o', 'r', 'W'])
>>> helloset.issubset(printset)
True
>>> set(bell).issubset(printset)
False

So, in summary, you would probably want to do this:

import string
printset = set(string.printable)
isprintable = set(yourstring).issubset(printset)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)