如您所说的
string module has 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
您可以将两个字符串转换为集合 – 因此该集合将包含字符串中的每个字符一次 – 并检查您的字符串is a subset of创建的集合是否是可打印字符:
>>> 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
所以,总而言之,你可能想这样做:
import string
printset = set(string.printable)
isprintable = set(yourstring).issubset(printset)