我有一个字符串,看起来有点像这样:
案例0:
string0 = ' '
案例一:
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 中)?
最佳答案
使用字符串方法 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 的循环确定所有不可打印字符或空格字符:
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
关于python - 如何检查字符串是否只包含不可打印的字符和空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66406380/