如何检查字符串是否只包含不可打印的字符和空格?

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

我有一个看起来有点像这样的字符串:

案例 0:

string0 = ' '

案例 1:

string1 = '\n\n'

案例 2:

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

案例 3:

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

案例4:

string4 = 'test string12!.'

我希望只允许在案例 3 和案例 4 中看到的情况。

使用 isprintable() 将不允许案例 3 通过并允许案例 0 通过。

如何检测字符串是否为空白(例如,在情况 0、情况 1 和情况 2 中)?

短语“不可打印字符”可能没有明确定义,但如果我们假设它只是空白字符,那么我们可以尝试匹配正则表达式模式 ^\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')

使用字符串方法 isprintable()isspace() 并遍历字符串以检查每个字符:

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')

输出:

Not Printable

对于包含可打印字符的字符串:

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')

输出:

Printable

您还可以使用改编自 here:

的循环确定所有不可打印或 space 字符
unprintable = []

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

然后确保字符串仅包含这些字符(在我的计算机上为 10158),如下所示:

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

输出:

Not Printable