我有一个看起来像这样的字符串:
case0:
string0 = ' '
case1:
string1 = 'nn'
例2:
string2 = 'nnn n nnnn'
case3:
string3 = ' test string12!. nn'
case4:
string4 = 'test string12!.'
我希望只允许情况3和情况4中的情况。
使用isprintable()
将不允许case 3通过,而允许case 0通过。
我如何检测字符串是否看起来是空白的(例如在情况0,情况1和情况2)?
使用字符串方法isprintable()
和isspace()
并遍历字符串以检查每个字符:
string1 = 'nn'
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!. nn'
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 = 'nnn n nnnn'
if set(string2).issubset(set(unprintable)):
print("Not Printable")
else:
print('Printable')
输出:
Not Printable
短语" unprintable character ";可能没有很好地定义,但是如果我们假设它只是空白字符,那么我们可以尝试匹配正则表达式模式^s+$
:
string2 = 'nnn n nnnn'
if re.search(r'^s+$', string2):
print('string 2 has only whitespace') # prints 'string 2 has only whitespace'
string3 = ' test string12!. nn'
if re.search(r'^s+$', string3):
print('string 3 has only whitespace')