如何检查一个字符串是否仅包含不可打印字符和空格?

3

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

case0:

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中)?

2个回答

1
使用字符串方法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

您还可以使用从此处改编的循环来确定所有不可打印或空格字符:

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

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接